org.bitcoinj.core.Sha256Hash Java Examples

The following examples show how to use org.bitcoinj.core.Sha256Hash. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TXUtil.java    From jelectrum with MIT License 6 votes vote down vote up
public void saveTxCache(Block block)
{

HashMap<Sha256Hash, Transaction> m = new HashMap<>(512, 0.5f);

for(Transaction tx : block.getTransactions())
{
	m.put(tx.getHash(), SerializedTransaction.scrubTransaction(params,tx));
}

synchronized(tx_cache_lock)
{
  	if (transaction_cache == null)
  	{
    	transaction_cache = new LRUCache<Sha256Hash, Transaction>(TX_CACHE_SIZE);
  	}
  	transaction_cache.putAll(m);
}
}
 
Example #2
Source File: EOSSign.java    From token-core-android with Apache License 2.0 6 votes vote down vote up
private static SignatureData signAsRecoverable(byte[] value, ECKey ecKey) {
  int recId = -1;
  ECKey.ECDSASignature sig = eosSign(value, ecKey.getPrivKey());
  for (int i = 0; i < 4; i++) {
    ECKey recoverKey = ECKey.recoverFromSignature(i, sig, Sha256Hash.wrap(value), false);
    if (recoverKey != null && recoverKey.getPubKeyPoint().equals(ecKey.getPubKeyPoint())) {
      recId = i;
      break;
    }
  }

  if (recId == -1) {
    throw new TokenException("Could not construct a recoverable key. This should never happen.");
  }
  int headerByte = recId + 27 + 4;
  // 1 header + 32 bytes for R + 32 bytes for S
  byte v = (byte) headerByte;
  byte[] r = NumericUtil.bigIntegerToBytesWithZeroPadded(sig.r, 32);
  byte[] s = NumericUtil.bigIntegerToBytesWithZeroPadded(sig.s, 32);

  return new SignatureData(v, r, s);

}
 
Example #3
Source File: LobstackMapSet.java    From jelectrum with MIT License 6 votes vote down vote up
public Set<Sha256Hash> getSet(String p, int max_results)
{
  try
  {
    HashSet<Sha256Hash> ret = new HashSet<Sha256Hash>();
    String search = p + "/";
    int len = search.length();
    int count = 0;
    for(String s : stack.getByPrefix(search).keySet())
    {
      ret.add(Sha256Hash.wrap(s.substring(len)));
      count ++;
      if (count > max_results) throw new DBTooManyResultsException();
    }
    return ret;
  }
  catch(java.io.IOException e){throw new RuntimeException(e);}
}
 
Example #4
Source File: Hash.java    From token-core-android with Apache License 2.0 6 votes vote down vote up
public static byte[] merkleHash(byte[] oriData) {

    if (oriData == null || oriData.length == 0) {
      throw new IllegalArgumentException("data should not be null");
    }
    int chunkSize = 1024;
    List<byte[]> hashes = new ArrayList<>();
    for (int pos = 0; pos < oriData.length; pos += chunkSize) {
      int end = Math.min(pos + chunkSize, oriData.length);
      hashes.add(Sha256Hash.hashTwice(Arrays.copyOfRange(oriData, pos, end)));
    }

    int j = 0;
    for (int size = hashes.size(); size > 1; size = (size + 1) / 2) {
      for (int i = 0; i < size; i += 2) {
        int i2 = Math.min(i + 1, size - 1);
        hashes.add(Sha256Hash.hashTwice(ByteUtil.concat(hashes.get(j + i), hashes.get(j + i2))));
      }
      j += size;
    }

    return hashes.get(hashes.size() - 1);
  }
 
Example #5
Source File: UtxoTrieNode.java    From jelectrum with MIT License 6 votes vote down vote up
public void printTree(PrintStream out, int indent, UtxoTrieMgr mgr)
{
  for(int i=0; i<indent; i++) out.print(" ");
  out.println("Node: ." + prefix +".");
  indent++;
  for(Map.Entry<String, Sha256Hash> me : springs.entrySet())
  {
    String sub = prefix + me.getKey();
    
    for(int i=0; i<indent; i++) out.print(" ");
    out.println(sub + " - " + me.getValue());
    if (sub.length() < UtxoTrieMgr.ADDR_SPACE*2)
    {
      mgr.getByKey(sub).printTree(out, indent+1, mgr);
    }

  }

}
 
Example #6
Source File: Importer.java    From jelectrum with MIT License 6 votes vote down vote up
public void saveBlock(Block b)
{
    try
    {
      Sha256Hash hash = b.getHash();
      needed_prev_blocks.offer(b.getPrevBlockHash());
      int h = block_store.getHeight(hash);

      synchronized(in_progress)
      {
        if (!in_progress.containsKey(hash))
        {
          in_progress.put(hash, new Semaphore(0));
        }
      }

      jelly.getEventLog().log("Enqueing block: " + hash + " - " + h); 
      block_queue.put(b);
    }
    catch(java.lang.InterruptedException e)
    {
        throw new RuntimeException(e);
    }

}
 
Example #7
Source File: MemPooler.java    From jelectrum with MIT License 6 votes vote down vote up
public boolean areSomeInputsPending(Transaction tx)
{
  MemPoolInfo info = latest_info;
  if (info == null) return false; //Hard to say

  for(TransactionInput tx_in : tx.getInputs())
  {
    if (!tx_in.isCoinBase())
    {
      TransactionOutPoint tx_out = tx_in.getOutpoint();
      Sha256Hash parent_hash = tx_out.getHash();
      if (info.tx_set.contains(parent_hash)) return true;
    }
  }
  return false;
}
 
Example #8
Source File: Main.java    From BitcoinWallet with MIT License 6 votes vote down vote up
private static void generateSegwitAddress(String address) {
    byte[] decoded = Utils.parseAsHexOrBase58(address);
    // We should throw off header byte that is 0 for Bitcoin (Main)
    byte[] pureBytes = new byte[20];
    System.arraycopy(decoded, 1, pureBytes, 0, 20);
    // Than we should prepend the following bytes:
    byte[] scriptSig = new byte[pureBytes.length + 2];
    scriptSig[0] = 0x00;
    scriptSig[1] = 0x14;
    System.arraycopy(pureBytes, 0, scriptSig, 2, pureBytes.length);
    byte[] addressBytes = org.bitcoinj.core.Utils.sha256hash160(scriptSig);
    // Here are the address bytes
    byte[] readyForAddress = new byte[addressBytes.length + 1 + 4];
    // prepending p2sh header:
    readyForAddress[0] = (byte) 5;
    System.arraycopy(addressBytes, 0, readyForAddress, 1, addressBytes.length);
    // But we should also append check sum:
    byte[] checkSum = Sha256Hash.hashTwice(readyForAddress, 0, addressBytes.length + 1);
    System.arraycopy(checkSum, 0, readyForAddress, addressBytes.length + 1, 4);
    // To get the final address:
    String segwitAddress = Base58.base58Encode(readyForAddress);
    System.out.println("segwit address:" + segwitAddress);
}
 
Example #9
Source File: SPV.java    From green_android with GNU General Public License v3.0 6 votes vote down vote up
private void addUtxoToValues(final Sha256Hash txHash, final boolean updateVerified) {
    final String txHashHex = txHash.toString();

    if (updateVerified)
        cfgEdit().putBoolean(PrefKeys.VERIFIED_HASH_ + txHashHex, true).apply();

    for (final SubaccountData subaccountData : mSubaccounts) {
        final Integer pointer = subaccountData.getPointer();
        try {
            final List<TransactionData> txs = getTransactions(pointer);
            //TODO called too many times
            for (final TransactionData tx : txs) {
                if (txHashHex.equals(tx.getTxhash())) {
                    //transactionDataObservable.fire();
                }
            }
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }
}
 
Example #10
Source File: TXUtil.java    From jelectrum with MIT License 5 votes vote down vote up
public Transaction getTransaction(Sha256Hash hash)
{ 
  long t1 = System.nanoTime();
  Transaction tx = null;
  synchronized(tx_cache_lock)
  {
    if (transaction_cache != null) 
    {
      tx = transaction_cache.get(hash);
    }
  }
  if (tx != null)
  {
    TimeRecord.record(t1, "txutil_gettx_cache");
    return tx;
  }

  SerializedTransaction s_tx = db.getTransaction(hash);

  if (s_tx != null)
  { 
    tx = s_tx.getTx(params);
    putTxCacheIfOpen(tx);
    TimeRecord.record(t1, "txutil_gettx_db");
    return tx;
  }
  return null;
}
 
Example #11
Source File: LevelDBFullPrunedBlockStore.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setVerifiedChainHead(StoredBlock chainHead) throws BlockStoreException {
    if (instrument)
        beginMethod("setVerifiedChainHead");
    Sha256Hash hash = chainHead.getHeader().getHash();
    this.verifiedChainHeadHash = hash;
    this.verifiedChainHeadBlock = chainHead;
    batchPut(getKey(KeyType.VERIFIED_CHAIN_HEAD_SETTING), hash.getBytes());
    if (this.chainHeadBlock.getHeight() < chainHead.getHeight())
        setChainHead(chainHead);
    removeUndoableBlocksWhereHeightIsLessThan(chainHead.getHeight() - fullStoreDepth);
    if (instrument)
        endMethod("setVerifiedChainHead");
}
 
Example #12
Source File: TransactionUtil.java    From chain33-sdk-java with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static Signature btcCoinSign(byte[] data, byte[] privateKey) {
	byte[] sha256 = TransactionUtil.Sha256(data);
	Sha256Hash sha256Hash = Sha256Hash.wrap(sha256);
	ECKey ecKey = ECKey.fromPrivate(privateKey);
	ECKey.ECDSASignature ecdsas = ecKey.sign(sha256Hash);
	byte[] signByte = ecdsas.encodeToDER();
	Signature signature = new Signature();
	signature.setPubkey(ecKey.getPubKey());
	signature.setSignature(signByte);
	signature.setTy(SignType.SECP256K1.getType());
	return signature;
}
 
Example #13
Source File: DB.java    From jelectrum with MIT License 5 votes vote down vote up
public SerializedTransaction getTransaction(Sha256Hash hash)
{
  return rawSource.getTransaction(hash);

  /*SerializedTransaction stx = getTransactionMap().get(hash);
  if (stx != null) return stx;

  //ok lets try to get it via block
  Set<Sha256Hash> block_hash_set = getTxToBlockMap(hash);
  if (block_hash_set == null) return null;

  for(Sha256Hash block_hash : block_hash_set)
  {
    SerializedBlock sb = getBlockMap().get(block_hash);
    if (sb != null)
    {
      Block b = sb.getBlock(network_params);

      for(Transaction tx : b.getTransactions())
      {
        if (tx.getHash().equals(hash))
        {
          return new SerializedTransaction(tx, b.getTime().getTime());
        }
      }

    }
 
  }

  return null;*/
}
 
Example #14
Source File: TxOutInfo.java    From consensusj with Apache License 2.0 5 votes vote down vote up
@JsonCreator
public TxOutInfo(@JsonProperty("bestblock")     Sha256Hash  bestblock,
                 @JsonProperty("confirmations") int         confirmations,
                 @JsonProperty("value")         Coin        value,
                 @JsonProperty("scriptPubKey")  Map         scriptPubKey,
                 @JsonProperty("version")       int         version,
                 @JsonProperty("coinbase")      boolean     coinbase) {
    this.bestblock = bestblock;
    this.confirmations = confirmations;
    this.value = value;
    this.scriptPubKey = scriptPubKey;
    this.version = version;
    this.coinbase = coinbase;
}
 
Example #15
Source File: Base58Util.java    From chain33-sdk-java with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Decodes the given base58 string into the original data bytes, using the checksum in the
 * last 4 bytes of the decoded data to verify that the rest are correct. The checksum is
 * removed from the returned data.
 *
 * @param input the base58-encoded string to decode (which should include the checksum)
 * @throws AddressFormatException if the input is not base 58 or the checksum does not validate.
 */
public static byte[] decodeChecked(String input) throws Exception {
    byte[] decoded  = decode(input);
    if (decoded.length < 4)
        throw new Exception("Input too short: "+ decoded.length);
    byte[] data = Arrays.copyOfRange(decoded, 0, decoded.length - 4);
    byte[] checksum = Arrays.copyOfRange(decoded, decoded.length - 4, decoded.length);
    byte[] actualChecksum = Arrays.copyOfRange(Sha256Hash.hashTwice(data), 0, 4);
    if (!Arrays.equals(checksum, actualChecksum))
        throw new Exception("error");
    return data;
}
 
Example #16
Source File: SPV.java    From GreenBits with GNU General Public License v3.0 5 votes vote down vote up
private void addToUtxo(final Sha256Hash txHash, final Integer prevIndex, final int subAccount, final int pointer) {
    mUnspentDetails.put(createOutPoint(prevIndex, txHash, mService.getNetworkParameters()),
                        new AccountInfo(subAccount, pointer));
    if (mUnspentOutpoints.get(txHash) == null)
        mUnspentOutpoints.put(txHash, Lists.newArrayList(prevIndex));
    else
        mUnspentOutpoints.get(txHash).add(prevIndex);
}
 
Example #17
Source File: LevelDBFullPrunedBlockStore.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
private byte[] getTxKey(KeyType keytype, Sha256Hash hash, int index) {
    byte[] key = new byte[37];

    key[0] = (byte) keytype.ordinal();
    System.arraycopy(hash.getBytes(), 0, key, 1, 32);
    byte[] heightBytes = ByteBuffer.allocate(4).putInt(index).array();
    System.arraycopy(heightBytes, 0, key, 33, 4);
    return key;
}
 
Example #18
Source File: BitcoinClient.java    From consensusj with Apache License 2.0 5 votes vote down vote up
/**
 * Get raw transaction info as hex->bitcoinj or verbose (json->POJO)
 * @param txid Transaction ID/hash
 * @param verbose `true` to return JSON transaction
 * @return  RawTransactionInfo if verbose, otherwise Transaction
 * @throws JsonRpcStatusException JSON RPC status exception
 * @throws IOException network error
 * @deprecated Use getRawTransaction or getRawTransactionInfo as appropriate
 */
@Deprecated
public Object getRawTransaction(Sha256Hash txid, Boolean verbose) throws JsonRpcStatusException, IOException {
    Object result;
    if (verbose) {
        result = getRawTransactionInfo(txid);    // Verbose means JSON
    } else {
        result = getRawTransaction(txid);  // Not-verbose is bitcoinj Transaction
    }
    return result;
}
 
Example #19
Source File: LevelDBMapSet.java    From jelectrum with MIT License 5 votes vote down vote up
public void addAll(Collection<Map.Entry<String, Sha256Hash> > lst)
{
  Map<String, ByteString> write_map = new TreeMap<String, ByteString>();

  for(Map.Entry<String, Sha256Hash> me : lst)
  {
    write_map.put(prefix + me.getKey() + "/" + me.getValue(), null);
  }
  
  c.putAll(write_map);

}
 
Example #20
Source File: WalletManager.java    From guarda-android-wallets with GNU General Public License v3.0 5 votes vote down vote up
private void setUTXO(List<UTXOItem> utxoList) {
    if (wallet == null) return;

    Address a;
    if (restFromWif) {
        a = wallet.getImportedKeys().get(0).toAddress(params);
    } else {
        a = wallet.currentReceiveAddress();
    }

    final List<UTXO> utxos = new ArrayList<>();

    for (UTXOItem utxo : utxoList) {
        Sha256Hash hash = Sha256Hash.wrap(utxo.getTxHash());
        utxos.add(new UTXO(hash, utxo.getTxOutputN(), Coin.valueOf(utxo.getSatoshiValue()),
                0, false, ScriptBuilder.createOutputScript(a)));
    }

    UTXOProvider utxoProvider = new UTXOProvider() {
        @Override
        public List<UTXO> getOpenTransactionOutputs(List<Address> addresses) throws UTXOProviderException {
            return utxos;
        }

        @Override
        public int getChainHeadHeight() throws UTXOProviderException {
            return Integer.MAX_VALUE;
        }

        @Override
        public NetworkParameters getParams() {
            return wallet.getParams();
        }
    };
    wallet.setUTXOProvider(utxoProvider);
}
 
Example #21
Source File: MeritConsensus.java    From bisq-core with GNU Affero General Public License v3.0 5 votes vote down vote up
@VisibleForTesting
static boolean isSignatureValid(byte[] signatureFromMerit, String pubKeyAsHex, String blindVoteTxId) {
    // We verify if signature of hash of blindVoteTxId is correct. EC key from first input for blind vote tx is
    // used for signature.
    if (pubKeyAsHex == null) {
        log.error("Error at getMeritStake: pubKeyAsHex is null");
        return false;
    }

    // TODO Check if a sig key was used multiple times for different voters
    // At the moment we don't impl. that to not add too much complexity and as we consider that
    // risk very low.

    boolean result = false;
    try {
        ECKey pubKey = ECKey.fromPublicOnly(Utilities.decodeFromHex(pubKeyAsHex));
        ECKey.ECDSASignature signature = ECKey.ECDSASignature.decodeFromDER(signatureFromMerit).toCanonicalised();
        Sha256Hash msg = Sha256Hash.wrap(blindVoteTxId);
        result = pubKey.verify(msg, signature);
    } catch (Throwable t) {
        log.error("Signature verification of issuance failed: " + t.toString());
    }
    if (!result) {
        log.error("Signature verification of issuance failed: blindVoteTxId={}, pubKeyAsHex={}",
                blindVoteTxId, pubKeyAsHex);
    }
    return result;
}
 
Example #22
Source File: DB.java    From jelectrum with MIT License 5 votes vote down vote up
public void addScriptHashToTxMap(Collection<ByteString> publicKeys, Sha256Hash hash)
{
  LinkedList<Map.Entry<ByteString, ByteString>> lst = new LinkedList<>();
  for(ByteString a : publicKeys)
  {
    lst.add(new SimpleEntry<ByteString, ByteString>(a, ByteString.copyFrom(hash.getBytes())));
  }
  pubkey_to_tx_map.addAll(lst);

}
 
Example #23
Source File: Importer.java    From jelectrum with MIT License 5 votes vote down vote up
public void putInternal(Transaction tx, Sha256Hash block_hash, StatusContext ctx)
{
  

  if (!file_db.needsDetails()) return;

    if (block_hash == null)
    {
      //ctx.setStatus("TX_SERIALIZE");
      //SerializedTransaction s_tx = new SerializedTransaction(tx, System.currentTimeMillis());
      //ctx.setStatus("TX_PUT");
      //file_db.getTransactionMap().put(tx.getHash(), s_tx);
    }

    boolean confirmed = (block_hash != null);

    ctx.setStatus("TX_GET_ADDR");
    Collection<ByteString> addrs = tx_util.getAllScriptHashes(tx, confirmed, null);

    Random rnd = new Random();

    ctx.setStatus("TX_SAVE_ADDRESS");
    file_db.addScriptHashToTxMap(addrs, tx.getHash());

    imported_transactions.incrementAndGet();
    int h = -1;
    if (block_hash != null)
    {
        ctx.setStatus("TX_GET_HEIGHT");
        h = block_store.getHeight(block_hash);
    }

    ctx.setStatus("TX_NOTIFY");
    jelly.getElectrumNotifier().notifyNewTransaction(addrs, h);
    ctx.setStatus("TX_DONE");

}
 
Example #24
Source File: Sha256HashDeserializer.java    From consensusj with Apache License 2.0 5 votes vote down vote up
@Override
public Sha256Hash deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    JsonToken token = p.getCurrentToken();
    switch (token) {
        case VALUE_STRING:
            return Sha256Hash.wrap(p.getValueAsString());
        default:
            return (Sha256Hash) ctxt.handleUnexpectedToken(Sha256Hash.class, p);
    }
}
 
Example #25
Source File: TradeWalletService.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Seller creates and signs payout transaction and adds signature of buyer to complete the transaction.
 *
 * @param depositTx                 deposit transaction
 * @param buyerSignature            DER encoded canonical signature of buyer
 * @param buyerPayoutAmount         payout amount for buyer
 * @param sellerPayoutAmount        payout amount for seller
 * @param buyerPayoutAddressString  address for buyer
 * @param sellerPayoutAddressString address for seller
 * @param multiSigKeyPair           seller's key pair for MultiSig
 * @param buyerPubKey               the public key of the buyer
 * @param sellerPubKey              the public key of the seller
 * @return the payout transaction
 * @throws AddressFormatException if the buyer or seller base58 address doesn't parse or its checksum is invalid
 * @throws TransactionVerificationException if there was an unexpected problem with the payout tx or its signatures
 * @throws WalletException if the seller's wallet is null or structurally inconsistent
 */
public Transaction sellerSignsAndFinalizesPayoutTx(Transaction depositTx,
                                                   byte[] buyerSignature,
                                                   Coin buyerPayoutAmount,
                                                   Coin sellerPayoutAmount,
                                                   String buyerPayoutAddressString,
                                                   String sellerPayoutAddressString,
                                                   DeterministicKey multiSigKeyPair,
                                                   byte[] buyerPubKey,
                                                   byte[] sellerPubKey)
        throws AddressFormatException, TransactionVerificationException, WalletException {
    Transaction payoutTx = createPayoutTx(depositTx, buyerPayoutAmount, sellerPayoutAmount, buyerPayoutAddressString, sellerPayoutAddressString);
    // MS redeemScript
    Script redeemScript = get2of2MultiSigRedeemScript(buyerPubKey, sellerPubKey);
    // MS output from prev. tx is index 0
    Sha256Hash sigHash = payoutTx.hashForSignature(0, redeemScript, Transaction.SigHash.ALL, false);
    checkNotNull(multiSigKeyPair, "multiSigKeyPair must not be null");
    if (multiSigKeyPair.isEncrypted()) {
        checkNotNull(aesKey);
    }
    ECKey.ECDSASignature sellerSignature = multiSigKeyPair.sign(sigHash, aesKey).toCanonicalised();
    TransactionSignature buyerTxSig = new TransactionSignature(ECKey.ECDSASignature.decodeFromDER(buyerSignature),
            Transaction.SigHash.ALL, false);
    TransactionSignature sellerTxSig = new TransactionSignature(sellerSignature, Transaction.SigHash.ALL, false);
    // Take care of order of signatures. Need to be reversed here. See comment below at getMultiSigRedeemScript (seller, buyer)
    Script inputScript = ScriptBuilder.createP2SHMultiSigInputScript(ImmutableList.of(sellerTxSig, buyerTxSig),
            redeemScript);
    TransactionInput input = payoutTx.getInput(0);
    input.setScriptSig(inputScript);
    WalletService.printTx("payoutTx", payoutTx);
    WalletService.verifyTransaction(payoutTx);
    WalletService.checkWalletConsistency(wallet);
    WalletService.checkScriptSig(payoutTx, input, 0);
    checkNotNull(input.getConnectedOutput(), "input.getConnectedOutput() must not be null");
    input.verify(input.getConnectedOutput());
    return payoutTx;
}
 
Example #26
Source File: WalletAppKitService.java    From consensusj with Apache License 2.0 5 votes vote down vote up
private static BlockInfo.Sha256HashList hashListFromTxList(List<Transaction> txList) {
    if (txList == null) {
        return null;
    } else {
        List<Sha256Hash> list = txList.stream()
                .map(Transaction::getTxId)
                .collect(Collectors.toList());
        return new BlockInfo.Sha256HashList(list);
    }
}
 
Example #27
Source File: DeterministicKeyChainTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void watchingChainArbitraryPath() throws UnreadableWalletException {
    Utils.setMockClock();
    DeterministicKey key1 = bip44chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    DeterministicKey key2 = bip44chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    DeterministicKey key3 = bip44chain.getKey(KeyChain.KeyPurpose.CHANGE);
    DeterministicKey key4 = bip44chain.getKey(KeyChain.KeyPurpose.CHANGE);

    DeterministicKey watchingKey = bip44chain.getWatchingKey();
    watchingKey = watchingKey.dropPrivateBytes().dropParent();
    watchingKey.setCreationTimeSeconds(100000);
    chain = DeterministicKeyChain.watch(watchingKey);
    assertEquals(100000, chain.getEarliestKeyCreationTime());
    chain.setLookaheadSize(10);
    chain.maybeLookAhead();

    assertEquals(key1.getPubKeyPoint(), chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).getPubKeyPoint());
    assertEquals(key2.getPubKeyPoint(), chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS).getPubKeyPoint());
    final DeterministicKey key = chain.getKey(KeyChain.KeyPurpose.CHANGE);
    assertEquals(key3.getPubKeyPoint(), key.getPubKeyPoint());
    try {
        // Can't sign with a key from a watching chain.
        key.sign(Sha256Hash.ZERO_HASH);
        fail();
    } catch (ECKey.MissingPrivateKeyException e) {
        // Ignored.
    }
    // Test we can serialize and deserialize a watching chain OK.
    List<Protos.Key> serialization = chain.serializeToProtobuf();
    checkSerialization(serialization, "watching-wallet-arbitrary-path-serialization.txt");
    chain = DeterministicKeyChain.fromProtobuf(serialization, null).get(0);
    final DeterministicKey rekey4 = chain.getKey(KeyChain.KeyPurpose.CHANGE);
    assertEquals(key4.getPubKeyPoint(), rekey4.getPubKeyPoint());
}
 
Example #28
Source File: BlockChainCache.java    From jelectrum with MIT License 5 votes vote down vote up
public void undumbSelf(NetworkParameters params, BlockStore block_store)
  throws org.bitcoinj.store.BlockStoreException
{
  Sha256Hash genesis_hash = params.getGenesisBlock().getHash();
  StoredBlock cur = block_store.get(head);
  synchronized(update_lock)
  {
    while(true)
    {
      int height = cur.getHeight();

      if (!height_map.containsKey(height))
      {
        System.out.println("Height map missing: " + height);
        height_map.put(height, cur.getHeader().getHash());
      }
      if (main_chain.contains(cur.getHeader().getHash()))
      {
        System.out.println("Main chain missing: " + height);
        main_chain.add(cur.getHeader().getHash());
      }
      
      if (cur.getHeader().getHash().equals(genesis_hash)) return;
      
      cur = cur.getPrev(block_store);

    }


  }

}
 
Example #29
Source File: DeterministicKeyChainTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void serializeUnencrypted() throws UnreadableWalletException {
    chain.maybeLookAhead();
    DeterministicKey key1 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    DeterministicKey key2 = chain.getKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
    DeterministicKey key3 = chain.getKey(KeyChain.KeyPurpose.CHANGE);
    List<Protos.Key> keys = chain.serializeToProtobuf();
    // 1 mnemonic/seed, 1 master key, 1 account key, 2 internal keys, 3 derived, 20 lookahead and 5 lookahead threshold.
    int numItems =
            1  // mnemonic/seed
                    + 1  // master key
                    + 1  // account key
                    + 2  // ext/int parent keys
                    + (chain.getLookaheadSize() + chain.getLookaheadThreshold()) * 2   // lookahead zone on each chain
            ;
    assertEquals(numItems, keys.size());

    // Get another key that will be lost during round-tripping, to ensure we can derive it again.
    DeterministicKey key4 = chain.getKey(KeyChain.KeyPurpose.CHANGE);

    final String EXPECTED_SERIALIZATION = checkSerialization(keys, "deterministic-wallet-serialization.txt");

    // Round trip the data back and forth to check it is preserved.
    int oldLookaheadSize = chain.getLookaheadSize();
    chain = DeterministicKeyChain.fromProtobuf(keys, null).get(0);
    assertEquals(EXPECTED_SERIALIZATION, protoToString(chain.serializeToProtobuf()));
    assertEquals(key1, chain.findKeyFromPubHash(key1.getPubKeyHash()));
    assertEquals(key2, chain.findKeyFromPubHash(key2.getPubKeyHash()));
    assertEquals(key3, chain.findKeyFromPubHash(key3.getPubKeyHash()));
    assertEquals(key4, chain.getKey(KeyChain.KeyPurpose.CHANGE));
    key1.sign(Sha256Hash.ZERO_HASH);
    key2.sign(Sha256Hash.ZERO_HASH);
    key3.sign(Sha256Hash.ZERO_HASH);
    key4.sign(Sha256Hash.ZERO_HASH);
    assertEquals(oldLookaheadSize, chain.getLookaheadSize());
}
 
Example #30
Source File: RawTransactionInfo.java    From consensusj with Apache License 2.0 5 votes vote down vote up
public Vin(@JsonProperty("txid") Sha256Hash txid,
           @JsonProperty("vout") long vout,
           @JsonProperty("scriptSig") Object scriptSig,
           @JsonProperty("sequence") long sequence) {
    this.txid = txid;
    this.vout = vout;
    this.scriptSig = scriptSig;
    this.sequence = sequence;
}