private void init(NetworkParameters params, byte[] seed, String passphrase) { this.params = params; this.seed = seed; strPassphrase = passphrase; byte[] hd_seed = MnemonicCode.toSeed(wordList, ""); dkKey = HDKeyDerivation.createMasterPrivateKey(hd_seed); DeterministicKey dKey = HDKeyDerivation.deriveChildKey(dkKey, 44 | ChildNumber.HARDENED_BIT); dkRoot = HDKeyDerivation.deriveChildKey(dKey, ChildNumber.HARDENED_BIT); int nbAccounts = 1; accounts = new ArrayList<Account>(); for(int i = 0; i < nbAccounts; i++) { accounts.add(new Account(params, dkRoot, i)); } strPath = dKey.getPathAsString(); }
@Override public CoinSelection select(Coin target, List<TransactionOutput> candidates) { ArrayList<TransactionOutput> selected = new ArrayList<>(); // Sort the inputs by age*value so we get the highest "coindays" spent. // TODO: Consider changing the wallets internal format to track just outputs and keep them ordered. ArrayList<TransactionOutput> sortedOutputs = new ArrayList<>(candidates); // When calculating the wallet balance, we may be asked to select all possible coins, if so, avoid sorting // them in order to improve performance. // TODO: Take in network parameters when instanatiated, and then test against the current network. Or just have a boolean parameter for "give me everything" if (!target.equals(NetworkParameters.MAX_MONEY)) { sortOutputs(sortedOutputs); } // Now iterate over the sorted outputs until we have got as close to the target as possible or a little // bit over (excessive value will be change). long total = 0; for (TransactionOutput output : sortedOutputs) { if (total >= target.value) break; // Only pick chain-included transactions, or transactions that are ours and pending. if (!shouldSelect(output.getParentTransaction())) continue; selected.add(output); total += output.getValue().value; } // Total may be lower than target here, if the given candidates were insufficient to create to requested // transaction. return new CoinSelection(Coin.valueOf(total), selected); }
public static Wallet restoreWalletFromProtobufOrBase58(final InputStream is, final NetworkParameters expectedNetworkParameters) throws IOException { is.mark((int) Constants.BACKUP_MAX_CHARS); try { return restoreWalletFromProtobuf(is, expectedNetworkParameters); } catch (final IOException x) { try { is.reset(); return restorePrivateKeysFromBase58(is, expectedNetworkParameters); } catch (final IOException x2) { throw new IOException( "cannot read protobuf (" + x.getMessage() + ") or base58 (" + x2.getMessage() + ")", x); } } }
public static Address getUserExternalAddress(final String pubKey, final NetworkParameters networkParameters, final long userIndex) { DeterministicKey deterministicKey = DeterministicKey.deserializeB58(pubKey, networkParameters); DeterministicHierarchy deterministicHierarchy = new DeterministicHierarchy(deterministicKey); List<ChildNumber> child = null; if (deterministicKey.getDepth() == 2) { /* M/44'/0' node tpub */ child = ImmutableList.of(new ChildNumber(0, false), new ChildNumber(1/*user*/, false), new ChildNumber(0/*external*/, false), new ChildNumber((int)userIndex, false)); } else if (deterministicKey.getDepth() == 3) { /* M/44'/0'/X context tpub */ child = ImmutableList.of(new ChildNumber(1/*user*/, false), new ChildNumber(0/*external*/, false), new ChildNumber((int)userIndex, false)); } DeterministicKey imprintingKey = deterministicHierarchy.get(child, true, true); return imprintingKey.toAddress(networkParameters); }
public static Address getUserInternalAddress(final String pubKey, final NetworkParameters networkParameters, final long userIndex) { DeterministicKey deterministicKey = DeterministicKey.deserializeB58(pubKey, networkParameters); DeterministicHierarchy deterministicHierarchy = new DeterministicHierarchy(deterministicKey); List<ChildNumber> child = null; if (deterministicKey.getDepth() == 2) { /* M/44'/0' node tpub */ child = ImmutableList.of(new ChildNumber(0, false), new ChildNumber(1/*user*/, false), new ChildNumber(1/*internal*/, false), new ChildNumber((int)userIndex, false)); } else if (deterministicKey.getDepth() == 3) { /* M/44'/0'/X context tpub */ child = ImmutableList.of(new ChildNumber(1/*user*/, false), new ChildNumber(1/*internal*/, false), new ChildNumber((int)userIndex, false)); } DeterministicKey imprintingKey = deterministicHierarchy.get(child, true, true); return imprintingKey.toAddress(networkParameters); }
public static Address getProviderExternalAddress(final String pubKey, final NetworkParameters networkParameters, final long providerIndex) { DeterministicKey deterministicKey = DeterministicKey.deserializeB58(pubKey, networkParameters); DeterministicHierarchy deterministicHierarchy = new DeterministicHierarchy(deterministicKey); List<ChildNumber> child = null; if (deterministicKey.getDepth() == 2) { /* M/44'/0' node tpub */ child = ImmutableList.of(new ChildNumber(0, false), new ChildNumber(0/*provider*/, false), new ChildNumber(/*external*/0, false), new ChildNumber((int)providerIndex, false)); } else if (deterministicKey.getDepth() == 3) { /* M/44'/0'/X context tpub */ child = ImmutableList.of(new ChildNumber(0/*provider*/, false), new ChildNumber(/*external*/0, false), new ChildNumber((int)providerIndex, false)); } DeterministicKey imprintingKey = deterministicHierarchy.get(child, true, true); return imprintingKey.toAddress(networkParameters); }
public static Address getProviderInternalAddress(final String pubKey, final NetworkParameters networkParameters, final long providerIndex) { DeterministicKey deterministicKey = DeterministicKey.deserializeB58(pubKey, networkParameters); DeterministicHierarchy deterministicHierarchy = new DeterministicHierarchy(deterministicKey); List<ChildNumber> child = null; if (deterministicKey.getDepth() == 2) { /* M/44'/0' node tpub */ child = ImmutableList.of(new ChildNumber(0, false), new ChildNumber(0/*provider*/, false), new ChildNumber(1/*internal*/, false), new ChildNumber((int)providerIndex, false)); } else if (deterministicKey.getDepth() == 3) { /* M/44'/0'/X context tpub */ child = ImmutableList.of(new ChildNumber(0/*provider*/, false), new ChildNumber(1/*internal*/, false), new ChildNumber((int)providerIndex, false)); } DeterministicKey imprintingKey = deterministicHierarchy.get(child, true, true); return imprintingKey.toAddress(networkParameters); }
public SQLiteBlockStore(NetworkParameters params, Context context) throws BlockStoreException { this.params = params; blocksDataSource = new BlocksDataSource(context); blocksDataSource.open(); if (blocksDataSource.count()==0){ createNewBlockStore(params); } else{ try { DBBlock block = blocksDataSource.getLast(); Block b = new Block(params, block.getHeader()); StoredBlock s = build(b); this.chainHead = s.getHeader().getHash(); } catch (Exception e) { throw new BlockStoreException("Invalid BlockStore chainHead"); } } blocksDataSource.close(); }
/** * Return true if the transaction in input is a valid imprinting transaction and contains the specified address in * one of its output, otherwise false. * @param tx the transaction to check if is valid imprinting * @param networkParameters the {@link NetworkParameters} * @param imprintingAddress the address to check for * @return true if it's an imprinting transaction otherwise false */ public static boolean isValidImprintingTransaction(Transaction tx, NetworkParameters networkParameters, Address imprintingAddress) { // Retrieve sender String sender = tx.getInput(0).getFromAddress().toBase58(); // Check output List<TransactionOutput> transactionOutputs = tx.getOutputs(); for (TransactionOutput to : transactionOutputs) { Address address = to.getAddressFromP2PKHScript(networkParameters); if (address != null && address.equals(imprintingAddress)) { return true; } } return false; }
public String toString(boolean includePrivateKeys, @Nullable KeyParameter aesKey, NetworkParameters params) { final DeterministicKey watchingKey = getWatchingKey(); final StringBuilder builder = new StringBuilder(); if (seed != null) { if (includePrivateKeys) { DeterministicSeed decryptedSeed = seed.isEncrypted() ? seed.decrypt(getKeyCrypter(), DEFAULT_PASSPHRASE_FOR_MNEMONIC, aesKey) : seed; final List<String> words = decryptedSeed.getMnemonicCode(); builder.append("Seed as words: ").append(Utils.SPACE_JOINER.join(words)).append('\n'); builder.append("Seed as hex: ").append(decryptedSeed.toHexString()).append('\n'); } else { if (seed.isEncrypted()) builder.append("Seed is encrypted\n"); } builder.append("Seed birthday: ").append(seed.getCreationTimeSeconds()).append(" [") .append(Utils.dateTimeFormat(seed.getCreationTimeSeconds() * 1000)).append("]\n"); } else { builder.append("Key birthday: ").append(watchingKey.getCreationTimeSeconds()).append(" [") .append(Utils.dateTimeFormat(watchingKey.getCreationTimeSeconds() * 1000)).append("]\n"); } builder.append("Key to watch: ").append(watchingKey.serializePubB58(params)).append('\n'); formatAddresses(includePrivateKeys, aesKey, params, builder); return builder.toString(); }
public LevelDBFullPrunedBlockStore(NetworkParameters params, String filename, int blockCount, long leveldbReadCache, int leveldbWriteCache, int openOutCache, boolean instrument, int exitBlock) { this.params = params; fullStoreDepth = blockCount; this.instrument = instrument; this.exitBlock = exitBlock; methodStartTime = new HashMap<>(); methodCalls = new HashMap<>(); methodTotalTime = new HashMap<>(); this.filename = filename; this.leveldbReadCache = leveldbReadCache; this.leveldbWriteCache = leveldbWriteCache; this.openOutCache = openOutCache; bloom = new BloomFilter(); totalStopwatch = Stopwatch.createStarted(); openDB(); bloom.reloadCache(db); // Reset after bloom filter loaded totalStopwatch = Stopwatch.createStarted(); }
@Test public void testBuild() throws Exception { UniquidWatchingNodeImpl.WatchingNodeBuilder builder = new UniquidWatchingNodeImpl.WatchingNodeBuilder(); NetworkParameters parameters = UniquidRegTest.get(); File providerFile = File.createTempFile("provider", ".wallet"); File userFile = File.createTempFile("user", ".wallet"); File chainFile = File.createTempFile("chain", ".chain"); File userChainFile = File.createTempFile("userchain", ".chain"); RegisterFactory dummyRegister = new DummyRegisterFactory(null, null, new DummyTransactionManager()); String machineName = "machineName"; builder.setNetworkParameters(parameters); builder.setProviderFile(providerFile); builder.setUserFile(userFile); builder.setProviderChainFile(chainFile); builder.setUserChainFile(userChainFile); builder.setRegisterFactory(dummyRegister); builder.setNodeName(machineName); UniquidWatchingNodeImpl uniquidNode = builder.buildFromXpub("tpubDAnD549eCz2j2w21P6sx9NvXJrEoWzVevpbvXDpwQzKTC9xWsr8emiEdJ64h1qXbYE4SbDJNbZ7imotNPsGD8RvHQvh6xtgMJTczb8WW8X8", 123456789); Assert.assertNotNull(uniquidNode); }
private Result analyzeIsStandard() { // The IsStandard rules don't apply on testnet, because they're just a safety mechanism and we don't want to // crush innovation with valueless test coins. if (wallet != null && !wallet.getNetworkParameters().getId().equals(NetworkParameters.ID_MAINNET)) return Result.OK; RuleViolation ruleViolation = isStandard(tx); if (ruleViolation != RuleViolation.NONE) { nonStandard = tx; return Result.NON_STANDARD; } for (Transaction dep : dependencies) { ruleViolation = isStandard(dep); if (ruleViolation != RuleViolation.NONE) { nonStandard = dep; return Result.NON_STANDARD; } } return Result.OK; }
/** * Constructor for account. * * @param NetworkParameters params * @param DeterministicKey mwey deterministic key for this account * @param int child id within the wallet for this account * */ public Account(NetworkParameters params, DeterministicKey wKey, int child) { this.params = params; aID = child; // L0PRV & STDVx: private derivation. int childnum = child; childnum |= ChildNumber.HARDENED_BIT; aKey = HDKeyDerivation.deriveChildKey(wKey, childnum); strXPUB = aKey.serializePubB58(params); chains = new ArrayList<Chain>(); chains.add(new Chain(params, aKey, true)); chains.add(new Chain(params, aKey, false)); strPath = aKey.getPathAsString(); }
/** * Builds a suitable set of peer discoveries. Will query them in parallel before producing a merged response. * If specific services are required, DNS is not used as the protocol can't handle it. * @param params Network to use. * @param services Required services as a bitmask, e.g. {@link VersionMessage#NODE_NETWORK}. */ public static MultiplexingDiscovery forServices(NetworkParameters params, long services) { List<PeerDiscovery> discoveries = Lists.newArrayList(); HttpDiscovery.Details[] httpSeeds = params.getHttpSeeds(); if (httpSeeds != null) { OkHttpClient httpClient = new OkHttpClient(); for (HttpDiscovery.Details httpSeed : httpSeeds) discoveries.add(new HttpDiscovery(params, httpSeed, httpClient)); } // Also use DNS seeds if there is no specific service requirement if (services == 0) { String[] dnsSeeds = params.getDnsSeeds(); if (dnsSeeds != null) for (String dnsSeed : dnsSeeds) discoveries.add(new DnsSeedDiscovery(params, dnsSeed)); } return new MultiplexingDiscovery(params, discoveries); }
private Wallet(Context context, KeyChainGroup keyChainGroup) { this.context = context; this.params = context.getParams(); this.keyChainGroup = checkNotNull(keyChainGroup); if (params.getId().equals(NetworkParameters.ID_UNITTESTNET)) this.keyChainGroup.setLookaheadSize(5); // Cut down excess computation for unit tests. // If this keyChainGroup was created fresh just now (new wallet), make HD so a backup can be made immediately // without having to call current/freshReceiveKey. If there are already keys in the chain of any kind then // we're probably being deserialized so leave things alone: the API user can upgrade later. if (this.keyChainGroup.numKeys() == 0) this.keyChainGroup.createAndActivateNewHDChain(); watchedScripts = Sets.newHashSet(); unspent = new HashMap<>(); spent = new HashMap<>(); pending = new HashMap<>(); dead = new HashMap<>(); transactions = new HashMap<>(); extensions = new HashMap<>(); // Use a linked hash map to ensure ordering of event listeners is correct. confidenceChanged = new LinkedHashMap<>(); signers = new ArrayList<>(); addTransactionSigner(new LocalTransactionSigner()); createTransientState(); }
/** * Returns the balance of this wallet as calculated by the provided balanceType. */ public Coin getBalance(BalanceType balanceType) { lock.lock(); try { if (balanceType == BalanceType.AVAILABLE || balanceType == BalanceType.AVAILABLE_SPENDABLE) { List<TransactionOutput> candidates = calculateAllSpendCandidates(true, balanceType == BalanceType.AVAILABLE_SPENDABLE); CoinSelection selection = coinSelector.select(NetworkParameters.MAX_MONEY, candidates); return selection.valueGathered; } else if (balanceType == BalanceType.ESTIMATED || balanceType == BalanceType.ESTIMATED_SPENDABLE) { List<TransactionOutput> all = calculateAllSpendCandidates(false, balanceType == BalanceType.ESTIMATED_SPENDABLE); Coin value = Coin.ZERO; for (TransactionOutput out : all) value = value.add(out.getValue()); return value; } else { throw new AssertionError("Unknown balance type"); // Unreachable. } } finally { lock.unlock(); } }
public synchronized void createNewBlockStore(NetworkParameters params) throws BlockStoreException { // Set up the genesis block. When we start out fresh, it is by definition the top of the chain. Block genesis = params.getGenesisBlock().cloneAsHeader(); StoredBlock storedGenesis = new StoredBlock(genesis, genesis.getWork(), 0); this.chainHead = storedGenesis.getHeader().getHash(); this.put(storedGenesis); }
public BitcoinAddressValidator(NetworkParameters params, TextField field, Node... nodes) { this.params = params; this.nodes = nodes; // Handle the red highlighting, but don't highlight in red just when the field is empty because that makes // the example/prompt address hard to read. new TextFieldValidator(field, text -> text.isEmpty() || testAddr(text)); // However we do want the buttons to be disabled when empty so we apply a different test there. field.textProperty().addListener((observableValue, prev, current) -> { toggleButtons(current); }); toggleButtons(field.getText()); }
public static void main(String[] args) { BriefLogFormatter.initWithSilentBitcoinJ(); ch.qos.logback.classic.Logger rootLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME); rootLogger.setLevel(Level.OFF); boolean generate = false; switch (args[0]) { case "generate": generate = true; break; default: System.out.println("Usage:\n generate: returns a new wallet " + "seed and creation time"); break; } if(generate){ final NetworkParameters params = TestNet3Params.get(); Context context = new Context(params); Wallet wallet = new Wallet(context); DeterministicSeed seed = wallet.getKeyChainSeed(); String seedString = seed.getMnemonicCode().toString(); System.out.println(seedString.substring(1,seedString.length()-1)); System.out.println(seed.getCreationTimeSeconds()); } }
@Override protected void formatAddresses(boolean includePrivateKeys, @Nullable KeyParameter aesKey, NetworkParameters params, StringBuilder builder2) { for (DeterministicKeyChain followingChain : followingKeyChains) builder2.append("Following chain: ").append(followingChain.getWatchingKey().serializePubB58(params)) .append('\n'); builder2.append('\n'); for (RedeemData redeemData : marriedKeysRedeemData.values()) formatScript(ScriptBuilder.createP2SHOutputScript(redeemData.redeemScript), builder2, params); }
public static boolean isSelectable(Transaction tx) { // Only pick chain-included transactions, or transactions that are ours and pending. TransactionConfidence confidence = tx.getConfidence(); TransactionConfidence.ConfidenceType type = confidence.getConfidenceType(); return type.equals(TransactionConfidence.ConfidenceType.BUILDING) || type.equals(TransactionConfidence.ConfidenceType.PENDING) && confidence.getSource().equals(TransactionConfidence.Source.SELF) && // In regtest mode we expect to have only one peer, so we won't see transactions propagate. // TODO: The value 1 below dates from a time when transactions we broadcast *to* were counted, set to 0 (confidence.numBroadcastPeers() > 1 || tx.getParams().getId().equals(NetworkParameters.ID_REGTEST)); }
@Test public void testBuild() throws Exception { @SuppressWarnings("rawtypes") UniquidNodeImpl.UniquidNodeBuilder builder = new UniquidNodeImpl.UniquidNodeBuilder(); NetworkParameters parameters = UniquidRegTest.get(); File providerFile = File.createTempFile("provider", ".wallet"); File userFile = File.createTempFile("user", ".wallet"); File chainFile = File.createTempFile("chain", ".chain"); File userChainFile = File.createTempFile("userchain", ".chain"); RegisterFactory dummyRegister = new DummyRegisterFactory(null, null, new DummyTransactionManager()); String machineName = "machineName"; builder.setNetworkParameters(parameters); builder.setProviderFile(providerFile); builder.setUserFile(userFile); builder.setProviderChainFile(chainFile); builder.setUserChainFile(userChainFile); builder.setRegisterFactory(dummyRegister); builder.setNodeName(machineName); UniquidNodeImpl uniquidNode = builder.build(); Assert.assertNotNull(uniquidNode); }
/** * * @param callbacks */ @Override public void execute(CoinActionCallback<CurrencyCoin>... callbacks) { this._callbacks = callbacks; NetworkParameters netParams = Constants.NETWORK_PARAMETERS; initWallet(netParams); _walletKit.setDownloadListener(this) .setBlockingStartup(false) .setCheckpoints(CheckpointManager.openStream(netParams)) .setUserAgent(ServiceConsts.SERVICE_APP_NAME, "0.1"); _walletKit.startAsync(); }
/** * */ private void initWallet(final NetworkParameters netParams) { //File dataDir = getDir("consensus_folder", Context.MODE_PRIVATE); // _bitcoinJContext = new org.bitcoinj.core.Context(netParams); // Start up a basic app using a class that automates some boilerplate. Ensure we always have at least one key. _walletKit = new WalletAppKit(Constants.NETWORK_PARAMETERS, _bitcoin.getDataDir(), ServiceConsts.SERVICE_APP_NAME + "-" + netParams.getPaymentProtocolId()) { /** * */ @Override protected void onSetupCompleted() { System.out.println("Setting up wallet : " + wallet().toString()); // This is called in a background thread after startAndWait is called, as setting up various objects // can do disk and network IO that may cause UI jank/stuttering in wallet apps if it were to be done // on the main thread. if (wallet().getKeyChainGroupSize() < 1) wallet().importKey(new ECKey()); peerGroup().setFastCatchupTimeSecs(wallet().getEarliestKeyCreationTime()); peerGroup().addPeerDiscovery(new DnsDiscovery(netParams)); // wallet.removeCoinsReceivedEventListener(_bitcoinManger); // wallet.addCoinsReceivedEventListener(_bitcoinManger); _bitcoin.setWalletManager(_walletKit); } }; }
public static Wallet restoreWalletFromProtobuf(final InputStream is, final NetworkParameters expectedNetworkParameters) throws IOException { try { final Wallet wallet = new WalletProtobufSerializer().readWallet(is, true, null); if (!wallet.getParams().equals(expectedNetworkParameters)) throw new IOException("bad wallet backup network parameters: " + wallet.getParams().getId()); if (!wallet.isConsistent()) throw new IOException("inconsistent wallet backup"); return wallet; } catch (final UnreadableWalletException x) { throw new IOException("unreadable wallet", x); } }
/** * Constructor for watch-only wallet initialized from submitted XPUB(s). * * @param NetworkParameters params * @param String[] xpub array of XPUB strings * */ public Wallet(NetworkParameters params, String[] xpub) throws AddressFormatException { this.params = params; accounts = new ArrayList<Account>(); for(int i = 0; i < xpub.length; i++) { accounts.add(new Account(params, xpub[i], i)); } }
/** * Constructor an HD address. * * @param NetworkParameters params * @param DeterministicKey cKey deterministic key for this address * @param int child index of this address in its chain * */ public Address(NetworkParameters params, DeterministicKey cKey, int child) { this.params = params; childNum = child; DeterministicKey dk = HDKeyDerivation.deriveChildKey(cKey, new ChildNumber(childNum, false)); // compressed WIF private key format if(dk.hasPrivKey()) { // byte[] prepended0Byte = ArrayUtils.addAll(new byte[1], dk.getPrivKeyBytes()); byte[] getPrivKeyBytes = dk.getPrivKeyBytes(); byte[] prepended0Byte = new byte[1 + getPrivKeyBytes.length]; prepended0Byte[0] = 0; System.arraycopy(getPrivKeyBytes, 0, prepended0Byte, 1, getPrivKeyBytes.length); ecKey = ECKey.fromPrivate(new BigInteger(prepended0Byte), true); } else { ecKey = ECKey.fromPublicOnly(dk.getPubKey()); } long now = Utils.now().getTime() / 1000; // use Unix time (in seconds) ecKey.setCreationTimeSeconds(now); pubKey = ecKey.getPubKey(); pubKeyHash = ecKey.getPubKeyHash(); strPath = dk.getPathAsString(); }
/** * Create new wallet. * * @param int nbWords number of words in menmonic * @param String passphrase optional BIP39 passphrase * @param int nbAccounts create this number of accounts * * @return Wallet * */ public Wallet newWallet(int nbWords, String passphrase, int nbAccounts) throws IOException, MnemonicException.MnemonicLengthException { Wallet hdw = null; if((nbWords % 3 != 0) || (nbWords < 12 || nbWords > 24)) { nbWords = 12; } // len == 16 (12 words), len == 24 (18 words), len == 32 (24 words) int len = (nbWords / 3) * 4; if(passphrase == null) { passphrase = ""; } NetworkParameters params = MainNetParams.get(); SecureRandom random = new SecureRandom(); byte seed[] = new byte[len]; random.nextBytes(seed); MnemonicCode mc = new MnemonicCode(); hdw = new Wallet(mc, params, seed, passphrase); wallets.clear(); wallets.add(hdw); return hdw; }
public Wallet restoreWalletFromJSON(JSONObject obj, String passPhrase) throws Exception { NetworkParameters params = MainNetParams.get(); Wallet wallet = new Wallet(obj, passPhrase, params); log("mnemonics: " + wallet.getMnemonic()); log("address: " + wallet.getAddress().getAddressString()); wallets.clear(); wallets.add(wallet); return wallet; }
/** * Constructor for a chain. * * @param NetworkParameters params * @param DeterministicKey aKey deterministic key for this chain * @param boolean isReceive this is the receive chain * */ public Chain(NetworkParameters params, DeterministicKey aKey, boolean isReceive) { this.params = params; this.isReceive = isReceive; int chain = isReceive ? 0 : 1; cKey = HDKeyDerivation.deriveChildKey(aKey, chain); strPath = cKey.getPathAsString(); }
@Test public void testWallet() throws UnreadableWalletException { long creationTimeSeconds = System.currentTimeMillis() / 1000; NetworkParameters params = MainNetParams.get(); String [] MNEMONIC = new String [] {"sword","acquire","little","despair","wave","swear","during","expect","target","science","banana","eyebrow"}; String RECEIVE_ADDRESS = "13w74gmmSjb2DWit5iRQbCKPZj89FkCidH"; String CHANGE_ADDRESS = "1hF37FtrcSyEFkyxo2Q3541aGfWRqsuLV"; List<String> fixedMnemonic = toMnemonic(MNEMONIC); printMnemonic(fixedMnemonic); DeterministicSeed ds2 = new DeterministicSeed(fixedMnemonic, null, "", creationTimeSeconds); KeyChainGroup fixedKeyChainFromSeed = new KeyChainGroup(params, ds2); Wallet fixedWallet = new Wallet(params, fixedKeyChainFromSeed); String fixedReceiveAddress = fixedWallet.currentReceiveAddress().toString(); String fixedChangeAddress = fixedWallet.currentChangeAddress().toString(); Assert.assertEquals(RECEIVE_ADDRESS, fixedReceiveAddress); Assert.assertEquals(CHANGE_ADDRESS, fixedChangeAddress); printAddress(fixedKeyChainFromSeed.currentAddress(KeyPurpose.AUTHENTICATION), "current auth address"); printAddress(fixedKeyChainFromSeed.currentAddress(KeyPurpose.CHANGE), "current change address"); printAddress(fixedKeyChainFromSeed.currentAddress(KeyPurpose.RECEIVE_FUNDS), "current receive address"); printAddress(fixedKeyChainFromSeed.currentAddress(KeyPurpose.REFUND), "current refund address"); for(int i = 0; i < 10; i++) { System.out.println("address[" + i + "]: "+ fixedKeyChainFromSeed.freshAddress(KeyPurpose.RECEIVE_FUNDS).toString()); } System.out.println("---------------"); String MNEMONIC_STRING = "sword acquire little despair wave swear during expect target science banana eyebrow"; DeterministicSeed seed = new DeterministicSeed(MNEMONIC_STRING, null, "", creationTimeSeconds); Wallet wallet = Wallet.fromSeed(params, seed); System.out.println("wallet receive address: " + wallet.currentReceiveAddress().toString()); }
@Test public void testWalletFromSeed() throws Exception { NetworkParameters params = MainNetParams.get(); MnemonicCode mc = new MnemonicCode(); Wallet wallet = new Wallet(mc, params, WALLET_SEED_BYTES, WALLET_PASS_PHRASE); assertEquals(WALLET_SEED, wallet.getSeedHex()); assertArrayEquals(WALLET_SEED_BYTES, wallet.getSeed()); assertEquals(WALLET_MNEMONIC, wallet.getMnemonic()); assertEquals(WALLET_PASS_PHRASE, wallet.getPassphrase()); }
public static SendRequest emptyWallet(Address destination) { SendRequest req = new SendRequest(); final NetworkParameters parameters = destination.getParameters(); checkNotNull(parameters, "Address is for an unknown network"); req.tx = new Transaction(parameters); req.tx.addOutput(Coin.ZERO, destination); req.emptyWallet = true; return req; }
public TransactionGenerator(NetworkParameters params, PeerGroup pg, Wallet w, BlockChain bc) { this.params = params; this.pg = pg; this.w = w; this.bc = bc; }
public boolean isPubKeyCorrect(NetworkParameters params) { byte[] pubkeyHashFromP2SHOutput; if(!ScriptBuilder.createP2SHOutputScript(sp.getRedeemScript()).equals(getLastTransactionOutput().getScriptPubKey())) { System.out.println("received redeemscript doesn't match the redeemscript hash of the transaction output, abort"); return false; } int chunklength = sp.getRedeemScript().getChunks().size(); pubkeyHashFromP2SHOutput = sp.getRedeemScript().getChunks().get(chunklength-3).data; return Arrays.equals(Utils.sha256hash160(sp.getPubKey()), pubkeyHashFromP2SHOutput); }
public Mixer(PTP ptp, BroadcastAnnouncement bca, ProofMessage pm, Wallet w, NetworkParameters params, PeerGroup pg, BlockChain bc) { this.ptp = ptp; this.bca = bca; this.mixPartnerAdress = new Identifier(bca.getOnionAdress() + ".onion"); this.ownProof = pm; this.w = w; this.params = params; this.pg = pg; this.bc = bc; this.mfListeners = new ArrayList<MixFinishedEventListener>(); this.lockTime = 0; }
public Mixer(PTP ptp, String onionAddress, ProofMessage pm, Wallet w, NetworkParameters params, PeerGroup pg, BlockChain bc) { this.ptp = ptp; this.mixPartnerAdress = new Identifier(onionAddress); this.ownProof = pm; this.w = w; this.params = params; this.pg = pg; this.bc = bc; this.mfListeners = new ArrayList<MixFinishedEventListener>(); this.lockTime = 0; }
public Mixer(PTP ptp, ProofMessage pm, Wallet w, NetworkParameters params, PeerGroup pg, BlockChain bc) { this.ptp = ptp; this.ownProof = pm; this.w = w; this.params = params; this.pg = pg; this.bc = bc; this.mfListeners = new ArrayList<MixFinishedEventListener>(); this.lockTime = 0; }