idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
33,700
private void cleanTable ( ) { lock . lock ( ) ; try { Reference < ? extends TransactionConfidence > ref ; while ( ( ref = referenceQueue . poll ( ) ) != null ) { WeakConfidenceReference txRef = ( WeakConfidenceReference ) ref ; table . remove ( txRef . hash ) ; } } finally { lock . unlock ( ) ; } }
If any transactions have expired due to being only weakly reachable through us go ahead and delete their table entries - it means we downloaded the transaction and sent it to various event listeners none of which bothered to keep a reference . Typically this is because the transaction does not involve any keys that are relevant to any of our wallets .
33,701
public int numBroadcastPeers ( Sha256Hash txHash ) { lock . lock ( ) ; try { cleanTable ( ) ; WeakConfidenceReference entry = table . get ( txHash ) ; if ( entry == null ) { return 0 ; } else { TransactionConfidence confidence = entry . get ( ) ; if ( confidence == null ) { table . remove ( txHash ) ; return 0 ; } else { return confidence . numBroadcastPeers ( ) ; } } } finally { lock . unlock ( ) ; } }
Returns the number of peers that have seen the given hash recently .
33,702
public static byte [ ] hash ( byte [ ] input , int offset , int length ) { MessageDigest digest = newDigest ( ) ; digest . update ( input , offset , length ) ; return digest . digest ( ) ; }
Calculates the SHA - 256 hash of the given byte range .
33,703
public static byte [ ] hashTwice ( byte [ ] input , int offset , int length ) { MessageDigest digest = newDigest ( ) ; digest . update ( input , offset , length ) ; return digest . digest ( digest . digest ( ) ) ; }
Calculates the SHA - 256 hash of the given byte range and then hashes the resulting hash again .
33,704
public static InventoryMessage with ( Transaction ... txns ) { checkArgument ( txns . length > 0 ) ; InventoryMessage result = new InventoryMessage ( txns [ 0 ] . getParams ( ) ) ; for ( Transaction tx : txns ) result . addTransaction ( tx ) ; return result ; }
Creates a new inv message for the given transactions .
33,705
public InetSocketAddress [ ] getPeers ( long services , long timeoutValue , TimeUnit timeoutUnit ) throws PeerDiscoveryException { if ( services != 0 ) throw new PeerDiscoveryException ( "Pre-determined peers cannot be filtered by services: " + services ) ; try { return allPeers ( ) ; } catch ( UnknownHostException e ) { throw new PeerDiscoveryException ( e ) ; } }
Returns an array containing all the Bitcoin nodes within the list .
33,706
public StoredBlock build ( Block block ) throws VerificationException { BigInteger chainWork = this . chainWork . add ( block . getWork ( ) ) ; int height = this . height + 1 ; return new StoredBlock ( block , chainWork , height ) ; }
Creates a new StoredBlock calculating the additional fields by adding to the values in this block .
33,707
public KeyParameter deriveKey ( CharSequence password ) throws KeyCrypterException { byte [ ] passwordBytes = null ; try { passwordBytes = convertToByteArray ( password ) ; byte [ ] salt = new byte [ 0 ] ; if ( scryptParameters . getSalt ( ) != null ) { salt = scryptParameters . getSalt ( ) . toByteArray ( ) ; } else { log . warn ( "You are using a ScryptParameters with no salt. Your encryption may be vulnerable to a dictionary attack." ) ; } final Stopwatch watch = Stopwatch . createStarted ( ) ; byte [ ] keyBytes = SCrypt . scrypt ( passwordBytes , salt , ( int ) scryptParameters . getN ( ) , scryptParameters . getR ( ) , scryptParameters . getP ( ) , KEY_LENGTH ) ; watch . stop ( ) ; log . info ( "Deriving key took {} for {} scrypt iterations." , watch , scryptParameters . getN ( ) ) ; return new KeyParameter ( keyBytes ) ; } catch ( Exception e ) { throw new KeyCrypterException ( "Could not generate key from password and salt." , e ) ; } finally { if ( passwordBytes != null ) { java . util . Arrays . fill ( passwordBytes , ( byte ) 0 ) ; } } }
Generate AES key .
33,708
public EncryptedData encrypt ( byte [ ] plainBytes , KeyParameter aesKey ) throws KeyCrypterException { checkNotNull ( plainBytes ) ; checkNotNull ( aesKey ) ; try { byte [ ] iv = new byte [ BLOCK_LENGTH ] ; secureRandom . nextBytes ( iv ) ; ParametersWithIV keyWithIv = new ParametersWithIV ( aesKey , iv ) ; BufferedBlockCipher cipher = new PaddedBufferedBlockCipher ( new CBCBlockCipher ( new AESEngine ( ) ) ) ; cipher . init ( true , keyWithIv ) ; byte [ ] encryptedBytes = new byte [ cipher . getOutputSize ( plainBytes . length ) ] ; final int length1 = cipher . processBytes ( plainBytes , 0 , plainBytes . length , encryptedBytes , 0 ) ; final int length2 = cipher . doFinal ( encryptedBytes , length1 ) ; return new EncryptedData ( iv , Arrays . copyOf ( encryptedBytes , length1 + length2 ) ) ; } catch ( Exception e ) { throw new KeyCrypterException ( "Could not encrypt bytes." , e ) ; } }
Password based encryption using AES - CBC 256 bits .
33,709
public byte [ ] decrypt ( EncryptedData dataToDecrypt , KeyParameter aesKey ) throws KeyCrypterException { checkNotNull ( dataToDecrypt ) ; checkNotNull ( aesKey ) ; try { ParametersWithIV keyWithIv = new ParametersWithIV ( new KeyParameter ( aesKey . getKey ( ) ) , dataToDecrypt . initialisationVector ) ; BufferedBlockCipher cipher = new PaddedBufferedBlockCipher ( new CBCBlockCipher ( new AESEngine ( ) ) ) ; cipher . init ( false , keyWithIv ) ; byte [ ] cipherBytes = dataToDecrypt . encryptedBytes ; byte [ ] decryptedBytes = new byte [ cipher . getOutputSize ( cipherBytes . length ) ] ; final int length1 = cipher . processBytes ( cipherBytes , 0 , cipherBytes . length , decryptedBytes , 0 ) ; final int length2 = cipher . doFinal ( decryptedBytes , length1 ) ; return Arrays . copyOf ( decryptedBytes , length1 + length2 ) ; } catch ( InvalidCipherTextException e ) { throw new KeyCrypterException . InvalidCipherText ( "Could not decrypt bytes" , e ) ; } catch ( RuntimeException e ) { throw new KeyCrypterException ( "Could not decrypt bytes" , e ) ; } }
Decrypt bytes previously encrypted with this class .
33,710
public static void init ( ) { logger = Logger . getLogger ( "" ) ; final Handler [ ] handlers = logger . getHandlers ( ) ; if ( handlers . length > 0 ) handlers [ 0 ] . setFormatter ( new BriefLogFormatter ( ) ) ; }
Configures JDK logging to use this class for everything .
33,711
public static NetworkParameters fromID ( String id ) { if ( id . equals ( ID_MAINNET ) ) { return MainNetParams . get ( ) ; } else if ( id . equals ( ID_TESTNET ) ) { return TestNet3Params . get ( ) ; } else if ( id . equals ( ID_UNITTESTNET ) ) { return UnitTestParams . get ( ) ; } else if ( id . equals ( ID_REGTEST ) ) { return RegTestParams . get ( ) ; } else { return null ; } }
Returns the network parameters for the given string ID or NULL if not recognized .
33,712
public static NetworkParameters fromPmtProtocolID ( String pmtProtocolId ) { if ( pmtProtocolId . equals ( PAYMENT_PROTOCOL_ID_MAINNET ) ) { return MainNetParams . get ( ) ; } else if ( pmtProtocolId . equals ( PAYMENT_PROTOCOL_ID_TESTNET ) ) { return TestNet3Params . get ( ) ; } else if ( pmtProtocolId . equals ( PAYMENT_PROTOCOL_ID_UNIT_TESTS ) ) { return UnitTestParams . get ( ) ; } else if ( pmtProtocolId . equals ( PAYMENT_PROTOCOL_ID_REGTEST ) ) { return RegTestParams . get ( ) ; } else { return null ; } }
Returns the network parameters for the given string paymentProtocolID or NULL if not recognized .
33,713
public boolean passesCheckpoint ( int height , Sha256Hash hash ) { Sha256Hash checkpointHash = checkpoints . get ( height ) ; return checkpointHash == null || checkpointHash . equals ( hash ) ; }
Returns true if the block height is either not a checkpoint or is a checkpoint and the hash matches .
33,714
public final MessageSerializer getDefaultSerializer ( ) { if ( null == this . defaultSerializer ) { synchronized ( this ) { if ( null == this . defaultSerializer ) { this . defaultSerializer = getSerializer ( false ) ; } } } return defaultSerializer ; }
Return the default serializer for this network . This is a shared serializer .
33,715
public EnumSet < Block . VerifyFlag > getBlockVerificationFlags ( final Block block , final VersionTally tally , final Integer height ) { final EnumSet < Block . VerifyFlag > flags = EnumSet . noneOf ( Block . VerifyFlag . class ) ; if ( block . isBIP34 ( ) ) { final Integer count = tally . getCountAtOrAbove ( Block . BLOCK_VERSION_BIP34 ) ; if ( null != count && count >= getMajorityEnforceBlockUpgrade ( ) ) { flags . add ( Block . VerifyFlag . HEIGHT_IN_COINBASE ) ; } } return flags ; }
The flags indicating which block validation tests should be applied to the given block . Enables support for alternative blockchains which enable tests based on different criteria .
33,716
public EnumSet < Script . VerifyFlag > getTransactionVerificationFlags ( final Block block , final Transaction transaction , final VersionTally tally , final Integer height ) { final EnumSet < Script . VerifyFlag > verifyFlags = EnumSet . noneOf ( Script . VerifyFlag . class ) ; if ( block . getTimeSeconds ( ) >= NetworkParameters . BIP16_ENFORCE_TIME ) verifyFlags . add ( Script . VerifyFlag . P2SH ) ; if ( block . getVersion ( ) >= Block . BLOCK_VERSION_BIP65 && tally . getCountAtOrAbove ( Block . BLOCK_VERSION_BIP65 ) > this . getMajorityEnforceBlockUpgrade ( ) ) { verifyFlags . add ( Script . VerifyFlag . CHECKLOCKTIMEVERIFY ) ; } return verifyFlags ; }
The flags indicating which script validation tests should be applied to the given transaction . Enables support for alternative blockchains which enable tests based on different criteria .
33,717
@ SuppressWarnings ( "unchecked" ) private void deserializeMessage ( ByteBuffer buff ) throws Exception { MessageType msg = ( MessageType ) prototype . newBuilderForType ( ) . mergeFrom ( ByteString . copyFrom ( buff ) ) . build ( ) ; resetTimeout ( ) ; handler . messageReceived ( this , msg ) ; }
Does set the buffers s position to its limit
33,718
public static boolean secKeyVerify ( byte [ ] seckey ) { Preconditions . checkArgument ( seckey . length == 32 ) ; ByteBuffer byteBuff = nativeECDSABuffer . get ( ) ; if ( byteBuff == null || byteBuff . capacity ( ) < seckey . length ) { byteBuff = ByteBuffer . allocateDirect ( seckey . length ) ; byteBuff . order ( ByteOrder . nativeOrder ( ) ) ; nativeECDSABuffer . set ( byteBuff ) ; } byteBuff . rewind ( ) ; byteBuff . put ( seckey ) ; r . lock ( ) ; try { return secp256k1_ec_seckey_verify ( byteBuff , Secp256k1Context . getContext ( ) ) == 1 ; } finally { r . unlock ( ) ; } }
libsecp256k1 Seckey Verify - returns 1 if valid 0 if invalid
33,719
public static byte [ ] privKeyTweakMul ( byte [ ] privkey , byte [ ] tweak ) throws AssertFailException { Preconditions . checkArgument ( privkey . length == 32 ) ; ByteBuffer byteBuff = nativeECDSABuffer . get ( ) ; if ( byteBuff == null || byteBuff . capacity ( ) < privkey . length + tweak . length ) { byteBuff = ByteBuffer . allocateDirect ( privkey . length + tweak . length ) ; byteBuff . order ( ByteOrder . nativeOrder ( ) ) ; nativeECDSABuffer . set ( byteBuff ) ; } byteBuff . rewind ( ) ; byteBuff . put ( privkey ) ; byteBuff . put ( tweak ) ; byte [ ] [ ] retByteArray ; r . lock ( ) ; try { retByteArray = secp256k1_privkey_tweak_mul ( byteBuff , Secp256k1Context . getContext ( ) ) ; } finally { r . unlock ( ) ; } byte [ ] privArr = retByteArray [ 0 ] ; int privLen = ( byte ) new BigInteger ( new byte [ ] { retByteArray [ 1 ] [ 0 ] } ) . intValue ( ) & 0xFF ; int retVal = new BigInteger ( new byte [ ] { retByteArray [ 1 ] [ 1 ] } ) . intValue ( ) ; assertEquals ( privArr . length , privLen , "Got bad pubkey length." ) ; assertEquals ( retVal , 1 , "Failed return value check." ) ; return privArr ; }
libsecp256k1 PrivKey Tweak - Mul - Tweak privkey by multiplying to it
33,720
public static byte [ ] pubKeyTweakAdd ( byte [ ] pubkey , byte [ ] tweak ) throws AssertFailException { Preconditions . checkArgument ( pubkey . length == 33 || pubkey . length == 65 ) ; ByteBuffer byteBuff = nativeECDSABuffer . get ( ) ; if ( byteBuff == null || byteBuff . capacity ( ) < pubkey . length + tweak . length ) { byteBuff = ByteBuffer . allocateDirect ( pubkey . length + tweak . length ) ; byteBuff . order ( ByteOrder . nativeOrder ( ) ) ; nativeECDSABuffer . set ( byteBuff ) ; } byteBuff . rewind ( ) ; byteBuff . put ( pubkey ) ; byteBuff . put ( tweak ) ; byte [ ] [ ] retByteArray ; r . lock ( ) ; try { retByteArray = secp256k1_pubkey_tweak_add ( byteBuff , Secp256k1Context . getContext ( ) , pubkey . length ) ; } finally { r . unlock ( ) ; } byte [ ] pubArr = retByteArray [ 0 ] ; int pubLen = ( byte ) new BigInteger ( new byte [ ] { retByteArray [ 1 ] [ 0 ] } ) . intValue ( ) & 0xFF ; int retVal = new BigInteger ( new byte [ ] { retByteArray [ 1 ] [ 1 ] } ) . intValue ( ) ; assertEquals ( pubArr . length , pubLen , "Got bad pubkey length." ) ; assertEquals ( retVal , 1 , "Failed return value check." ) ; return pubArr ; }
libsecp256k1 PubKey Tweak - Add - Tweak pubkey by adding to it
33,721
public static byte [ ] createECDHSecret ( byte [ ] seckey , byte [ ] pubkey ) throws AssertFailException { Preconditions . checkArgument ( seckey . length <= 32 && pubkey . length <= 65 ) ; ByteBuffer byteBuff = nativeECDSABuffer . get ( ) ; if ( byteBuff == null || byteBuff . capacity ( ) < 32 + pubkey . length ) { byteBuff = ByteBuffer . allocateDirect ( 32 + pubkey . length ) ; byteBuff . order ( ByteOrder . nativeOrder ( ) ) ; nativeECDSABuffer . set ( byteBuff ) ; } byteBuff . rewind ( ) ; byteBuff . put ( seckey ) ; byteBuff . put ( pubkey ) ; byte [ ] [ ] retByteArray ; r . lock ( ) ; try { retByteArray = secp256k1_ecdh ( byteBuff , Secp256k1Context . getContext ( ) , pubkey . length ) ; } finally { r . unlock ( ) ; } byte [ ] resArr = retByteArray [ 0 ] ; int retVal = new BigInteger ( new byte [ ] { retByteArray [ 1 ] [ 0 ] } ) . intValue ( ) ; assertEquals ( resArr . length , 32 , "Got bad result length." ) ; assertEquals ( retVal , 1 , "Failed return value check." ) ; return resArr ; }
libsecp256k1 create ECDH secret - constant time ECDH calculation
33,722
public static synchronized boolean randomize ( byte [ ] seed ) throws AssertFailException { Preconditions . checkArgument ( seed . length == 32 || seed == null ) ; ByteBuffer byteBuff = nativeECDSABuffer . get ( ) ; if ( byteBuff == null || byteBuff . capacity ( ) < seed . length ) { byteBuff = ByteBuffer . allocateDirect ( seed . length ) ; byteBuff . order ( ByteOrder . nativeOrder ( ) ) ; nativeECDSABuffer . set ( byteBuff ) ; } byteBuff . rewind ( ) ; byteBuff . put ( seed ) ; w . lock ( ) ; try { return secp256k1_context_randomize ( byteBuff , Secp256k1Context . getContext ( ) ) == 1 ; } finally { w . unlock ( ) ; } }
libsecp256k1 randomize - updates the context randomization
33,723
public static PartialMerkleTree buildFromLeaves ( NetworkParameters params , byte [ ] includeBits , List < Sha256Hash > allLeafHashes ) { int height = 0 ; while ( getTreeWidth ( allLeafHashes . size ( ) , height ) > 1 ) height ++ ; List < Boolean > bitList = new ArrayList < > ( ) ; List < Sha256Hash > hashes = new ArrayList < > ( ) ; traverseAndBuild ( height , 0 , allLeafHashes , includeBits , bitList , hashes ) ; byte [ ] bits = new byte [ ( int ) Math . ceil ( bitList . size ( ) / 8.0 ) ] ; for ( int i = 0 ; i < bitList . size ( ) ; i ++ ) if ( bitList . get ( i ) ) Utils . setBitLE ( bits , i ) ; return new PartialMerkleTree ( params , bits , hashes , allLeafHashes . size ( ) ) ; }
Calculates a PMT given the list of leaf hashes and which leaves need to be included . The relevant interior hashes are calculated and a new PMT returned .
33,724
private Sha256Hash recursiveExtractHashes ( int height , int pos , ValuesUsed used , List < Sha256Hash > matchedHashes ) throws VerificationException { if ( used . bitsUsed >= matchedChildBits . length * 8 ) { throw new VerificationException ( "PartialMerkleTree overflowed its bits array" ) ; } boolean parentOfMatch = checkBitLE ( matchedChildBits , used . bitsUsed ++ ) ; if ( height == 0 || ! parentOfMatch ) { if ( used . hashesUsed >= hashes . size ( ) ) { throw new VerificationException ( "PartialMerkleTree overflowed its hash array" ) ; } Sha256Hash hash = hashes . get ( used . hashesUsed ++ ) ; if ( height == 0 && parentOfMatch ) matchedHashes . add ( hash ) ; return hash ; } else { byte [ ] left = recursiveExtractHashes ( height - 1 , pos * 2 , used , matchedHashes ) . getBytes ( ) , right ; if ( pos * 2 + 1 < getTreeWidth ( transactionCount , height - 1 ) ) { right = recursiveExtractHashes ( height - 1 , pos * 2 + 1 , used , matchedHashes ) . getBytes ( ) ; if ( Arrays . equals ( right , left ) ) throw new VerificationException ( "Invalid merkle tree with duplicated left/right branches" ) ; } else { right = left ; } return combineLeftRight ( left , right ) ; } }
it returns the hash of the respective node .
33,725
public Sha256Hash getTxnHashAndMerkleRoot ( List < Sha256Hash > matchedHashesOut ) throws VerificationException { matchedHashesOut . clear ( ) ; if ( transactionCount == 0 ) throw new VerificationException ( "Got a CPartialMerkleTree with 0 transactions" ) ; if ( transactionCount > Block . MAX_BLOCK_SIZE / 60 ) throw new VerificationException ( "Got a CPartialMerkleTree with more transactions than is possible" ) ; if ( hashes . size ( ) > transactionCount ) throw new VerificationException ( "Got a CPartialMerkleTree with more hashes than transactions" ) ; if ( matchedChildBits . length * 8 < hashes . size ( ) ) throw new VerificationException ( "Got a CPartialMerkleTree with fewer matched bits than hashes" ) ; int height = 0 ; while ( getTreeWidth ( transactionCount , height ) > 1 ) height ++ ; ValuesUsed used = new ValuesUsed ( ) ; Sha256Hash merkleRoot = recursiveExtractHashes ( height , 0 , used , matchedHashesOut ) ; if ( ( used . bitsUsed + 7 ) / 8 != matchedChildBits . length || used . hashesUsed != hashes . size ( ) ) throw new VerificationException ( "Got a CPartialMerkleTree that didn't need all the data it provided" ) ; return merkleRoot ; }
Extracts tx hashes that are in this merkle tree and returns the merkle root of this tree .
33,726
public synchronized long getRefundTransactionUnlockTime ( ) { checkState ( getState ( ) . compareTo ( State . WAITING_FOR_MULTISIG_CONTRACT ) > 0 && getState ( ) != State . ERROR ) ; return refundTransactionUnlockTimeSecs ; }
Gets the client s refund transaction which they can spend to get the entire channel value back if it reaches its lock time .
33,727
public void receiveMessage ( Protos . TwoWayChannelMessage msg ) { lock . lock ( ) ; try { checkState ( connectionOpen ) ; if ( channelSettling ) return ; try { switch ( msg . getType ( ) ) { case CLIENT_VERSION : receiveVersionMessage ( msg ) ; return ; case PROVIDE_REFUND : receiveRefundMessage ( msg ) ; return ; case PROVIDE_CONTRACT : receiveContractMessage ( msg ) ; return ; case UPDATE_PAYMENT : checkState ( step == InitStep . CHANNEL_OPEN && msg . hasUpdatePayment ( ) ) ; receiveUpdatePaymentMessage ( msg . getUpdatePayment ( ) , true ) ; return ; case CLOSE : receiveCloseMessage ( ) ; return ; case ERROR : checkState ( msg . hasError ( ) ) ; log . error ( "Client sent ERROR {} with explanation {}" , msg . getError ( ) . getCode ( ) . name ( ) , msg . getError ( ) . hasExplanation ( ) ? msg . getError ( ) . getExplanation ( ) : "" ) ; conn . destroyConnection ( CloseReason . REMOTE_SENT_ERROR ) ; return ; default : final String errorText = "Got unknown message type or type that doesn't apply to servers." ; error ( errorText , Protos . Error . ErrorCode . SYNTAX_ERROR , CloseReason . REMOTE_SENT_INVALID_MESSAGE ) ; } } catch ( VerificationException e ) { log . error ( "Caught verification exception handling message from client" , e ) ; error ( e . getMessage ( ) , Protos . Error . ErrorCode . BAD_TRANSACTION , CloseReason . REMOTE_SENT_INVALID_MESSAGE ) ; } catch ( ValueOutOfRangeException e ) { log . error ( "Caught value out of range exception handling message from client" , e ) ; error ( e . getMessage ( ) , Protos . Error . ErrorCode . BAD_TRANSACTION , CloseReason . REMOTE_SENT_INVALID_MESSAGE ) ; } catch ( InsufficientMoneyException e ) { log . error ( "Caught insufficient money exception handling message from client" , e ) ; error ( e . getMessage ( ) , Protos . Error . ErrorCode . BAD_TRANSACTION , CloseReason . REMOTE_SENT_INVALID_MESSAGE ) ; } catch ( SignatureDecodeException e ) { log . error ( "Caught illegal state exception handling message from client" , e ) ; error ( e . getMessage ( ) , Protos . Error . ErrorCode . SYNTAX_ERROR , CloseReason . REMOTE_SENT_INVALID_MESSAGE ) ; } } finally { lock . unlock ( ) ; } }
Called when a message is received from the client . Processes the given message and generates events based on its content .
33,728
public void bindAndStart ( int port ) throws Exception { server = new NioServer ( new StreamConnectionFactory ( ) { public ProtobufConnection < Protos . TwoWayChannelMessage > getNewConnection ( InetAddress inetAddress , int port ) { return new ServerHandler ( new InetSocketAddress ( inetAddress , port ) , timeoutSeconds ) . socketProtobufHandler ; } } , new InetSocketAddress ( port ) ) ; server . startAsync ( ) ; server . awaitRunning ( ) ; }
Binds to the given port and starts accepting new client connections .
33,729
public void closeConnection ( ) { checkState ( ! lock . isHeldByCurrentThread ( ) ) ; try { channel . close ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } connectionClosed ( ) ; }
May NOT be called with lock held
33,730
public static void handleKey ( SelectionKey key ) { ConnectionHandler handler = ( ( ConnectionHandler ) key . attachment ( ) ) ; try { if ( handler == null ) return ; if ( ! key . isValid ( ) ) { handler . closeConnection ( ) ; return ; } if ( key . isReadable ( ) ) { int read = handler . channel . read ( handler . readBuff ) ; if ( read == 0 ) return ; else if ( read == - 1 ) { key . cancel ( ) ; handler . closeConnection ( ) ; return ; } handler . readBuff . flip ( ) ; int bytesConsumed = checkNotNull ( handler . connection ) . receiveBytes ( handler . readBuff ) ; checkState ( handler . readBuff . position ( ) == bytesConsumed ) ; handler . readBuff . compact ( ) ; } if ( key . isWritable ( ) ) handler . tryWriteBytes ( ) ; } catch ( Exception e ) { Throwable t = Throwables . getRootCause ( e ) ; log . warn ( "Error handling SelectionKey: {} {}" , t . getClass ( ) . getName ( ) , t . getMessage ( ) != null ? t . getMessage ( ) : "" , e ) ; handler . closeConnection ( ) ; } }
atomically for a given ConnectionHandler )
33,731
public byte [ ] getProgram ( ) { try { if ( program != null ) return Arrays . copyOf ( program , program . length ) ; ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; for ( ScriptChunk chunk : chunks ) { chunk . write ( bos ) ; } program = bos . toByteArray ( ) ; return program ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }
Returns the serialized program as a newly created byte array .
33,732
public Address getToAddress ( NetworkParameters params , boolean forcePayToPubKey ) throws ScriptException { if ( ScriptPattern . isP2PKH ( this ) ) return LegacyAddress . fromPubKeyHash ( params , ScriptPattern . extractHashFromP2PKH ( this ) ) ; else if ( ScriptPattern . isP2SH ( this ) ) return LegacyAddress . fromScriptHash ( params , ScriptPattern . extractHashFromP2SH ( this ) ) ; else if ( forcePayToPubKey && ScriptPattern . isP2PK ( this ) ) return LegacyAddress . fromKey ( params , ECKey . fromPublicOnly ( ScriptPattern . extractKeyFromP2PK ( this ) ) ) ; else if ( ScriptPattern . isP2WH ( this ) ) return SegwitAddress . fromHash ( params , ScriptPattern . extractHashFromP2WH ( this ) ) ; else throw new ScriptException ( ScriptError . SCRIPT_ERR_UNKNOWN_ERROR , "Cannot cast this script to an address" ) ; }
Gets the destination address from this script if it s in the required form .
33,733
public Script getScriptSigWithSignature ( Script scriptSig , byte [ ] sigBytes , int index ) { int sigsPrefixCount = 0 ; int sigsSuffixCount = 0 ; if ( ScriptPattern . isP2SH ( this ) ) { sigsPrefixCount = 1 ; sigsSuffixCount = 1 ; } else if ( ScriptPattern . isSentToMultisig ( this ) ) { sigsPrefixCount = 1 ; } else if ( ScriptPattern . isP2PKH ( this ) ) { sigsSuffixCount = 1 ; } return ScriptBuilder . updateScriptWithSignature ( scriptSig , sigBytes , index , sigsPrefixCount , sigsSuffixCount ) ; }
Returns a copy of the given scriptSig with the signature inserted in the given position .
33,734
public int getSigInsertionIndex ( Sha256Hash hash , ECKey signingKey ) { List < ScriptChunk > existingChunks = chunks . subList ( 1 , chunks . size ( ) - 1 ) ; ScriptChunk redeemScriptChunk = chunks . get ( chunks . size ( ) - 1 ) ; checkNotNull ( redeemScriptChunk . data ) ; Script redeemScript = new Script ( redeemScriptChunk . data ) ; int sigCount = 0 ; int myIndex = redeemScript . findKeyInRedeem ( signingKey ) ; for ( ScriptChunk chunk : existingChunks ) { if ( chunk . opcode == OP_0 ) { } else { checkNotNull ( chunk . data ) ; try { if ( myIndex < redeemScript . findSigInRedeem ( chunk . data , hash ) ) return sigCount ; } catch ( SignatureDecodeException e ) { } sigCount ++ ; } } return sigCount ; }
Returns the index where a signature by the key should be inserted . Only applicable to a P2SH scriptSig .
33,735
public List < ECKey > getPubKeys ( ) { if ( ! ScriptPattern . isSentToMultisig ( this ) ) throw new ScriptException ( ScriptError . SCRIPT_ERR_UNKNOWN_ERROR , "Only usable for multisig scripts." ) ; ArrayList < ECKey > result = Lists . newArrayList ( ) ; int numKeys = Script . decodeFromOpN ( chunks . get ( chunks . size ( ) - 2 ) . opcode ) ; for ( int i = 0 ; i < numKeys ; i ++ ) result . add ( ECKey . fromPublicOnly ( chunks . get ( 1 + i ) . data ) ) ; return result ; }
Returns a list of the keys required by this script assuming a multi - sig script .
33,736
public static long getP2SHSigOpCount ( byte [ ] scriptSig ) throws ScriptException { Script script = new Script ( ) ; try { script . parse ( scriptSig ) ; } catch ( ScriptException e ) { } for ( int i = script . chunks . size ( ) - 1 ; i >= 0 ; i -- ) if ( ! script . chunks . get ( i ) . isOpCode ( ) ) { Script subScript = new Script ( ) ; subScript . parse ( script . chunks . get ( i ) . data ) ; return getSigOpCount ( subScript . chunks , true ) ; } return 0 ; }
Gets the count of P2SH Sig Ops in the Script scriptSig
33,737
public int getNumberOfSignaturesRequiredToSpend ( ) { if ( ScriptPattern . isSentToMultisig ( this ) ) { ScriptChunk nChunk = chunks . get ( 0 ) ; return Script . decodeFromOpN ( nChunk . opcode ) ; } else if ( ScriptPattern . isP2PKH ( this ) || ScriptPattern . isP2PK ( this ) ) { return 1 ; } else if ( ScriptPattern . isP2SH ( this ) ) { throw new IllegalStateException ( "For P2SH number of signatures depends on redeem script" ) ; } else { throw new IllegalStateException ( "Unsupported script type" ) ; } }
Returns number of signatures required to satisfy this script .
33,738
public static byte [ ] removeAllInstancesOf ( byte [ ] inputScript , byte [ ] chunkToRemove ) { UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream ( inputScript . length ) ; int cursor = 0 ; while ( cursor < inputScript . length ) { boolean skip = equalsRange ( inputScript , cursor , chunkToRemove ) ; int opcode = inputScript [ cursor ++ ] & 0xFF ; int additionalBytes = 0 ; if ( opcode >= 0 && opcode < OP_PUSHDATA1 ) { additionalBytes = opcode ; } else if ( opcode == OP_PUSHDATA1 ) { additionalBytes = ( 0xFF & inputScript [ cursor ] ) + 1 ; } else if ( opcode == OP_PUSHDATA2 ) { additionalBytes = Utils . readUint16 ( inputScript , cursor ) + 2 ; } else if ( opcode == OP_PUSHDATA4 ) { additionalBytes = ( int ) Utils . readUint32 ( inputScript , cursor ) + 4 ; } if ( ! skip ) { try { bos . write ( opcode ) ; bos . write ( Arrays . copyOfRange ( inputScript , cursor , cursor + additionalBytes ) ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } cursor += additionalBytes ; } return bos . toByteArray ( ) ; }
Returns the script bytes of inputScript with all instances of the specified script object removed
33,739
private static void executeCheckLockTimeVerify ( Transaction txContainingThis , int index , LinkedList < byte [ ] > stack , Set < VerifyFlag > verifyFlags ) throws ScriptException { if ( stack . size ( ) < 1 ) throw new ScriptException ( ScriptError . SCRIPT_ERR_INVALID_STACK_OPERATION , "Attempted OP_CHECKLOCKTIMEVERIFY on a stack with size < 1" ) ; final BigInteger nLockTime = castToBigInteger ( stack . getLast ( ) , 5 , verifyFlags . contains ( VerifyFlag . MINIMALDATA ) ) ; if ( nLockTime . compareTo ( BigInteger . ZERO ) < 0 ) throw new ScriptException ( ScriptError . SCRIPT_ERR_NEGATIVE_LOCKTIME , "Negative locktime" ) ; if ( ! ( ( ( txContainingThis . getLockTime ( ) < Transaction . LOCKTIME_THRESHOLD ) && ( nLockTime . compareTo ( Transaction . LOCKTIME_THRESHOLD_BIG ) ) < 0 ) || ( ( txContainingThis . getLockTime ( ) >= Transaction . LOCKTIME_THRESHOLD ) && ( nLockTime . compareTo ( Transaction . LOCKTIME_THRESHOLD_BIG ) ) >= 0 ) ) ) throw new ScriptException ( ScriptError . SCRIPT_ERR_UNSATISFIED_LOCKTIME , "Locktime requirement type mismatch" ) ; if ( nLockTime . compareTo ( BigInteger . valueOf ( txContainingThis . getLockTime ( ) ) ) > 0 ) throw new ScriptException ( ScriptError . SCRIPT_ERR_UNSATISFIED_LOCKTIME , "Locktime requirement not satisfied" ) ; if ( ! txContainingThis . getInput ( index ) . hasSequence ( ) ) throw new ScriptException ( ScriptError . SCRIPT_ERR_UNSATISFIED_LOCKTIME , "Transaction contains a final transaction input for a CHECKLOCKTIMEVERIFY script." ) ; }
This is more or less a direct translation of the code in Bitcoin Core
33,740
public static int getOpCode ( String opCodeName ) { if ( opCodeNameMap . containsKey ( opCodeName ) ) return opCodeNameMap . get ( opCodeName ) ; return OP_INVALIDOPCODE ; }
Converts the given OpCodeName into an int
33,741
public static RedeemData of ( ECKey key , Script redeemScript ) { checkArgument ( ScriptPattern . isP2PKH ( redeemScript ) || ScriptPattern . isP2WPKH ( redeemScript ) || ScriptPattern . isP2PK ( redeemScript ) ) ; return key != null ? new RedeemData ( Collections . singletonList ( key ) , redeemScript ) : null ; }
Creates RedeemData for P2PKH P2WPKH or P2PK input . Provided key is a single private key needed to spend such inputs .
33,742
public synchronized boolean isSettlementTransaction ( Transaction tx ) { try { tx . verify ( ) ; tx . getInput ( 0 ) . verify ( getContractInternal ( ) . getOutput ( 0 ) ) ; return true ; } catch ( VerificationException e ) { return false ; } }
Returns true if the tx is a valid settlement transaction .
33,743
synchronized void fakeSave ( ) { try { wallet . commitTx ( getContractInternal ( ) ) ; } catch ( VerificationException e ) { throw new RuntimeException ( e ) ; } stateMachine . transition ( State . PROVIDE_MULTISIG_CONTRACT_TO_SERVER ) ; }
Skips saving state in the wallet for testing
33,744
private static byte [ ] encode ( int witnessVersion , byte [ ] witnessProgram ) throws AddressFormatException { byte [ ] convertedProgram = convertBits ( witnessProgram , 0 , witnessProgram . length , 8 , 5 , true ) ; byte [ ] bytes = new byte [ 1 + convertedProgram . length ] ; bytes [ 0 ] = ( byte ) ( Script . encodeToOpN ( witnessVersion ) & 0xff ) ; System . arraycopy ( convertedProgram , 0 , bytes , 1 , convertedProgram . length ) ; return bytes ; }
Helper for the above constructor .
33,745
private static byte [ ] convertBits ( final byte [ ] in , final int inStart , final int inLen , final int fromBits , final int toBits , final boolean pad ) throws AddressFormatException { int acc = 0 ; int bits = 0 ; ByteArrayOutputStream out = new ByteArrayOutputStream ( 64 ) ; final int maxv = ( 1 << toBits ) - 1 ; final int max_acc = ( 1 << ( fromBits + toBits - 1 ) ) - 1 ; for ( int i = 0 ; i < inLen ; i ++ ) { int value = in [ i + inStart ] & 0xff ; if ( ( value >>> fromBits ) != 0 ) { throw new AddressFormatException ( String . format ( "Input value '%X' exceeds '%d' bit size" , value , fromBits ) ) ; } acc = ( ( acc << fromBits ) | value ) & max_acc ; bits += fromBits ; while ( bits >= toBits ) { bits -= toBits ; out . write ( ( acc >>> bits ) & maxv ) ; } } if ( pad ) { if ( bits > 0 ) out . write ( ( acc << ( toBits - bits ) ) & maxv ) ; } else if ( bits >= fromBits || ( ( acc << ( toBits - bits ) ) & maxv ) != 0 ) { throw new AddressFormatException ( "Could not convert bits, invalid padding" ) ; } return out . toByteArray ( ) ; }
Helper for re - arranging bits into groups .
33,746
protected synchronized SendRequest makeUnsignedChannelContract ( Coin valueToMe ) { Transaction tx = new Transaction ( wallet . getParams ( ) ) ; if ( ! getTotalValue ( ) . subtract ( valueToMe ) . equals ( Coin . ZERO ) ) { tx . addOutput ( getTotalValue ( ) . subtract ( valueToMe ) , LegacyAddress . fromKey ( wallet . getParams ( ) , getClientKey ( ) ) ) ; } tx . addInput ( contract . getOutput ( 0 ) ) ; return SendRequest . forTx ( tx ) ; }
Create a payment transaction with valueToMe going back to us
33,747
public synchronized boolean incrementPayment ( Coin refundSize , byte [ ] signatureBytes ) throws SignatureDecodeException , VerificationException , ValueOutOfRangeException , InsufficientMoneyException { stateMachine . checkState ( State . READY ) ; checkNotNull ( refundSize ) ; checkNotNull ( signatureBytes ) ; TransactionSignature signature = TransactionSignature . decodeFromBitcoin ( signatureBytes , true , false ) ; final boolean fullyUsedUp = refundSize . equals ( Coin . ZERO ) ; Coin newValueToMe = getTotalValue ( ) . subtract ( refundSize ) ; if ( newValueToMe . signum ( ) < 0 ) throw new ValueOutOfRangeException ( "Attempt to refund more than the contract allows." ) ; if ( newValueToMe . compareTo ( bestValueToMe ) < 0 ) throw new ValueOutOfRangeException ( "Attempt to roll back payment on the channel." ) ; SendRequest req = makeUnsignedChannelContract ( newValueToMe ) ; if ( ! fullyUsedUp && refundSize . isLessThan ( req . tx . getOutput ( 0 ) . getMinNonDustValue ( ) ) ) throw new ValueOutOfRangeException ( "Attempt to refund negative value or value too small to be accepted by the network" ) ; Transaction walletContract = wallet . getTransaction ( contract . getTxId ( ) ) ; checkNotNull ( walletContract , "Wallet did not contain multisig contract {} after state was marked READY" , contract . getTxId ( ) ) ; if ( walletContract . getConfidence ( ) . getConfidenceType ( ) == TransactionConfidence . ConfidenceType . DEAD ) { close ( ) ; throw new VerificationException ( "Multisig contract was double-spent" ) ; } Transaction . SigHash mode ; if ( fullyUsedUp ) mode = Transaction . SigHash . NONE ; else mode = Transaction . SigHash . SINGLE ; if ( signature . sigHashMode ( ) != mode || ! signature . anyoneCanPay ( ) ) throw new VerificationException ( "New payment signature was not signed with the right SIGHASH flags." ) ; Sha256Hash sighash = req . tx . hashForSignature ( 0 , getSignedScript ( ) , mode , true ) ; if ( ! getClientKey ( ) . verify ( sighash , signature ) ) throw new VerificationException ( "Signature does not verify on tx\n" + req . tx ) ; bestValueToMe = newValueToMe ; bestValueSignature = signatureBytes ; updateChannelInWallet ( ) ; return ! fullyUsedUp ; }
Called when the client provides us with a new signature and wishes to increment total payment by size . Verifies the provided signature and only updates values if everything checks out . If the new refundSize is not the lowest we have seen it is simply ignored .
33,748
protected int scale ( BigInteger satoshis , int fractionPlaces ) { int places ; int coinOffset = Math . max ( SMALLEST_UNIT_EXPONENT - fractionPlaces , 0 ) ; BigDecimal inCoins = new BigDecimal ( satoshis ) . movePointLeft ( coinOffset ) ; if ( inCoins . remainder ( ONE ) . compareTo ( ZERO ) == 0 ) { places = COIN_SCALE ; } else { BigDecimal inMillis = inCoins . movePointRight ( MILLICOIN_SCALE ) ; if ( inMillis . remainder ( ONE ) . compareTo ( ZERO ) == 0 ) { places = MILLICOIN_SCALE ; } else { BigDecimal inMicros = inCoins . movePointRight ( MICROCOIN_SCALE ) ; if ( inMicros . remainder ( ONE ) . compareTo ( ZERO ) == 0 ) { places = MICROCOIN_SCALE ; } else { BigDecimal a = inCoins . subtract ( inCoins . setScale ( 0 , HALF_UP ) ) . movePointRight ( coinOffset ) . abs ( ) ; BigDecimal b = inMillis . subtract ( inMillis . setScale ( 0 , HALF_UP ) ) . movePointRight ( coinOffset - MILLICOIN_SCALE ) . abs ( ) ; BigDecimal c = inMicros . subtract ( inMicros . setScale ( 0 , HALF_UP ) ) . movePointRight ( coinOffset - MICROCOIN_SCALE ) . abs ( ) ; if ( a . compareTo ( b ) < 0 ) if ( a . compareTo ( c ) < 0 ) places = COIN_SCALE ; else places = MICROCOIN_SCALE ; else if ( b . compareTo ( c ) < 0 ) places = MILLICOIN_SCALE ; else places = MICROCOIN_SCALE ; } } } prefixUnitsIndicator ( numberFormat , places ) ; return places ; }
Calculate the appropriate denomination for the given Bitcoin monetary value . This method takes a BigInteger representing a quantity of satoshis and returns the number of places that value s decimal point is to be moved when formatting said value in order that the resulting number represents the correct quantity of denominational units .
33,749
public List < Sha256Hash > getTransactionHashes ( ) throws VerificationException { if ( cachedTransactionHashes != null ) return Collections . unmodifiableList ( cachedTransactionHashes ) ; List < Sha256Hash > hashesMatched = new LinkedList < > ( ) ; if ( header . getMerkleRoot ( ) . equals ( merkleTree . getTxnHashAndMerkleRoot ( hashesMatched ) ) ) { cachedTransactionHashes = hashesMatched ; return Collections . unmodifiableList ( cachedTransactionHashes ) ; } else throw new VerificationException ( "Merkle root of block header does not match merkle root of partial merkle tree." ) ; }
Gets a list of leaf hashes which are contained in the partial merkle tree in this filtered block
33,750
public boolean provideTransaction ( Transaction tx ) throws VerificationException { Sha256Hash hash = tx . getTxId ( ) ; if ( getTransactionHashes ( ) . contains ( hash ) ) { associatedTransactions . put ( hash , tx ) ; return true ; } return false ; }
Provide this FilteredBlock with a transaction which is in its Merkle tree .
33,751
public static PaymentSession parsePaymentRequest ( Protos . PaymentRequest paymentRequest ) throws PaymentProtocolException { return new PaymentSession ( paymentRequest , false , null ) ; }
Parse a payment request .
33,752
public static void signPaymentRequest ( Protos . PaymentRequest . Builder paymentRequest , X509Certificate [ ] certificateChain , PrivateKey privateKey ) { try { final Protos . X509Certificates . Builder certificates = Protos . X509Certificates . newBuilder ( ) ; for ( final Certificate certificate : certificateChain ) certificates . addCertificate ( ByteString . copyFrom ( certificate . getEncoded ( ) ) ) ; paymentRequest . setPkiType ( "x509+sha256" ) ; paymentRequest . setPkiData ( certificates . build ( ) . toByteString ( ) ) ; paymentRequest . setSignature ( ByteString . EMPTY ) ; final Protos . PaymentRequest paymentRequestToSign = paymentRequest . build ( ) ; final String algorithm ; if ( "RSA" . equalsIgnoreCase ( privateKey . getAlgorithm ( ) ) ) algorithm = "SHA256withRSA" ; else throw new IllegalStateException ( privateKey . getAlgorithm ( ) ) ; final Signature signature = Signature . getInstance ( algorithm ) ; signature . initSign ( privateKey ) ; signature . update ( paymentRequestToSign . toByteArray ( ) ) ; paymentRequest . setSignature ( ByteString . copyFrom ( signature . sign ( ) ) ) ; } catch ( final GeneralSecurityException x ) { throw new RuntimeException ( x ) ; } }
Sign the provided payment request .
33,753
public static List < Transaction > parseTransactionsFromPaymentMessage ( NetworkParameters params , Protos . Payment paymentMessage ) { final List < Transaction > transactions = new ArrayList < > ( paymentMessage . getTransactionsCount ( ) ) ; for ( final ByteString transaction : paymentMessage . getTransactionsList ( ) ) transactions . add ( params . getDefaultSerializer ( ) . makeTransaction ( transaction . toByteArray ( ) ) ) ; return transactions ; }
Parse transactions from payment message .
33,754
public static Ack parsePaymentAck ( Protos . PaymentACK paymentAck ) { final String memo = paymentAck . hasMemo ( ) ? paymentAck . getMemo ( ) : null ; return new Ack ( memo ) ; }
Parse payment ack into an object .
33,755
public static ImmutableList < ChildNumber > append ( List < ChildNumber > path , ChildNumber childNumber ) { return ImmutableList . < ChildNumber > builder ( ) . addAll ( path ) . add ( childNumber ) . build ( ) ; }
Append a derivation level to an existing path
33,756
public static ImmutableList < ChildNumber > concat ( List < ChildNumber > path , List < ChildNumber > path2 ) { return ImmutableList . < ChildNumber > builder ( ) . addAll ( path ) . addAll ( path2 ) . build ( ) ; }
Concatenate two derivation paths
33,757
public Sha256Hash getTxId ( ) { if ( cachedTxId == null ) { if ( ! hasWitnesses ( ) && cachedWTxId != null ) { cachedTxId = cachedWTxId ; } else { ByteArrayOutputStream stream = new UnsafeByteArrayOutputStream ( length < 32 ? 32 : length + 32 ) ; try { bitcoinSerializeToStream ( stream , false ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } cachedTxId = Sha256Hash . wrapReversed ( Sha256Hash . hashTwice ( stream . toByteArray ( ) ) ) ; } } return cachedTxId ; }
Returns the transaction id as you see them in block explorers . It is used as a reference by transaction inputs via outpoints .
33,758
public int getWeight ( ) { if ( ! hasWitnesses ( ) ) return getMessageSize ( ) * 4 ; try ( final ByteArrayOutputStream stream = new UnsafeByteArrayOutputStream ( length ) ) { bitcoinSerializeToStream ( stream , false ) ; final int baseSize = stream . size ( ) ; stream . reset ( ) ; bitcoinSerializeToStream ( stream , true ) ; final int totalSize = stream . size ( ) ; return baseSize * 3 + totalSize ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }
Gets the transaction weight as defined in BIP141 .
33,759
public Coin getInputSum ( ) { Coin inputTotal = Coin . ZERO ; for ( TransactionInput input : inputs ) { Coin inputValue = input . getValue ( ) ; if ( inputValue != null ) { inputTotal = inputTotal . add ( inputValue ) ; } } return inputTotal ; }
Gets the sum of the inputs regardless of who owns them .
33,760
public Coin getValueSentToMe ( TransactionBag transactionBag ) { Coin v = Coin . ZERO ; for ( TransactionOutput o : outputs ) { if ( ! o . isMineOrWatched ( transactionBag ) ) continue ; v = v . add ( o . getValue ( ) ) ; } return v ; }
Calculates the sum of the outputs that are sending coins to a key in the wallet .
33,761
public Coin getValueSentFromMe ( TransactionBag wallet ) throws ScriptException { Coin v = Coin . ZERO ; for ( TransactionInput input : inputs ) { TransactionOutput connected = input . getConnectedOutput ( wallet . getTransactionPool ( Pool . UNSPENT ) ) ; if ( connected == null ) connected = input . getConnectedOutput ( wallet . getTransactionPool ( Pool . SPENT ) ) ; if ( connected == null ) connected = input . getConnectedOutput ( wallet . getTransactionPool ( Pool . PENDING ) ) ; if ( connected == null ) continue ; if ( ! connected . isMineOrWatched ( wallet ) ) continue ; v = v . add ( connected . getValue ( ) ) ; } return v ; }
Calculates the sum of the inputs that are spending coins with keys in the wallet . This requires the transactions sending coins to those keys to be in the wallet . This method will not attempt to download the blocks containing the input transactions if the key is in the wallet but the transactions are not .
33,762
public Coin getOutputSum ( ) { Coin totalOut = Coin . ZERO ; for ( TransactionOutput output : outputs ) { totalOut = totalOut . add ( output . getValue ( ) ) ; } return totalOut ; }
Gets the sum of the outputs of the transaction . If the outputs are less than the inputs it does not count the fee .
33,763
public Coin getFee ( ) { Coin fee = Coin . ZERO ; if ( inputs . isEmpty ( ) || outputs . isEmpty ( ) ) return null ; for ( TransactionInput input : inputs ) { if ( input . getValue ( ) == null ) return null ; fee = fee . add ( input . getValue ( ) ) ; } for ( TransactionOutput output : outputs ) { fee = fee . subtract ( output . getValue ( ) ) ; } return fee ; }
The transaction fee is the difference of the value of all inputs and the value of all outputs . Currently the fee can only be determined for transactions created by us .
33,764
public boolean isEveryOwnedOutputSpent ( TransactionBag transactionBag ) { for ( TransactionOutput output : outputs ) { if ( output . isAvailableForSpending ( ) && output . isMineOrWatched ( transactionBag ) ) return false ; } return true ; }
Returns false if this transaction has at least one output that is owned by the given wallet and unspent true otherwise .
33,765
public boolean isMature ( ) { if ( ! isCoinBase ( ) ) return true ; if ( getConfidence ( ) . getConfidenceType ( ) != ConfidenceType . BUILDING ) return false ; return getConfidence ( ) . getDepthInBlocks ( ) >= params . getSpendableCoinbaseDepth ( ) ; }
A transaction is mature if it is either a building coinbase tx that is as deep or deeper than the required coinbase depth or a non - coinbase tx .
33,766
public void clearInputs ( ) { unCache ( ) ; for ( TransactionInput input : inputs ) { input . setParent ( null ) ; } inputs . clear ( ) ; this . length = this . unsafeBitcoinSerialize ( ) . length ; }
Removes all the inputs from this transaction . Note that this also invalidates the length attribute
33,767
public TransactionInput addInput ( TransactionInput input ) { unCache ( ) ; input . setParent ( this ) ; inputs . add ( input ) ; adjustLength ( inputs . size ( ) , input . length ) ; return input ; }
Adds an input directly with no checking that it s valid .
33,768
public TransactionInput addInput ( Sha256Hash spendTxHash , long outputIndex , Script script ) { return addInput ( new TransactionInput ( params , this , script . getProgram ( ) , new TransactionOutPoint ( params , outputIndex , spendTxHash ) ) ) ; }
Creates and adds an input to this transaction with no checking that it s valid .
33,769
public void clearOutputs ( ) { unCache ( ) ; for ( TransactionOutput output : outputs ) { output . setParent ( null ) ; } outputs . clear ( ) ; this . length = this . unsafeBitcoinSerialize ( ) . length ; }
Removes all the outputs from this transaction . Note that this also invalidates the length attribute
33,770
public TransactionOutput addOutput ( TransactionOutput to ) { unCache ( ) ; to . setParent ( this ) ; outputs . add ( to ) ; adjustLength ( outputs . size ( ) , to . length ) ; return to ; }
Adds the given output to this transaction . The output must be completely initialized . Returns the given output .
33,771
public TransactionOutput addOutput ( Coin value , Address address ) { return addOutput ( new TransactionOutput ( params , this , value , address ) ) ; }
Creates an output based on the given address and value adds it to this transaction and returns the new output .
33,772
public TransactionOutput addOutput ( Coin value , Script script ) { return addOutput ( new TransactionOutput ( params , this , value , script . getProgram ( ) ) ) ; }
Creates an output that pays to the given script . The address and key forms are specialisations of this method you won t normally need to use it unless you re doing unusual things .
33,773
public Sha256Hash hashForSignature ( int inputIndex , byte [ ] connectedScript , byte sigHashType ) { try { Transaction tx = this . params . getDefaultSerializer ( ) . makeTransaction ( this . bitcoinSerialize ( ) ) ; for ( int i = 0 ; i < tx . inputs . size ( ) ; i ++ ) { TransactionInput input = tx . inputs . get ( i ) ; input . clearScriptBytes ( ) ; input . setWitness ( null ) ; } connectedScript = Script . removeAllInstancesOfOp ( connectedScript , ScriptOpCodes . OP_CODESEPARATOR ) ; TransactionInput input = tx . inputs . get ( inputIndex ) ; input . setScriptBytes ( connectedScript ) ; if ( ( sigHashType & 0x1f ) == SigHash . NONE . value ) { tx . outputs = new ArrayList < > ( 0 ) ; for ( int i = 0 ; i < tx . inputs . size ( ) ; i ++ ) if ( i != inputIndex ) tx . inputs . get ( i ) . setSequenceNumber ( 0 ) ; } else if ( ( sigHashType & 0x1f ) == SigHash . SINGLE . value ) { if ( inputIndex >= tx . outputs . size ( ) ) { return Sha256Hash . wrap ( "0100000000000000000000000000000000000000000000000000000000000000" ) ; } tx . outputs = new ArrayList < > ( tx . outputs . subList ( 0 , inputIndex + 1 ) ) ; for ( int i = 0 ; i < inputIndex ; i ++ ) tx . outputs . set ( i , new TransactionOutput ( tx . params , tx , Coin . NEGATIVE_SATOSHI , new byte [ ] { } ) ) ; for ( int i = 0 ; i < tx . inputs . size ( ) ; i ++ ) if ( i != inputIndex ) tx . inputs . get ( i ) . setSequenceNumber ( 0 ) ; } if ( ( sigHashType & SigHash . ANYONECANPAY . value ) == SigHash . ANYONECANPAY . value ) { tx . inputs = new ArrayList < > ( ) ; tx . inputs . add ( input ) ; } ByteArrayOutputStream bos = new ByteArrayOutputStream ( tx . length ) ; tx . bitcoinSerializeToStream ( bos , false ) ; uint32ToByteStreamLE ( 0x000000ff & sigHashType , bos ) ; Sha256Hash hash = Sha256Hash . twiceOf ( bos . toByteArray ( ) ) ; bos . close ( ) ; return hash ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }
This is required for signatures which use a sigHashType which cannot be represented using SigHash and anyoneCanPay See transaction c99c49da4c38af669dea436d3e73780dfdb6c1ecf9958baa52960e8baee30e73 which has sigHashType 0
33,774
public int getSigOpCount ( ) throws ScriptException { int sigOps = 0 ; for ( TransactionInput input : inputs ) sigOps += Script . getSigOpCount ( input . getScriptBytes ( ) ) ; for ( TransactionOutput output : outputs ) sigOps += Script . getSigOpCount ( output . getScriptBytes ( ) ) ; return sigOps ; }
Gets the count of regular SigOps in this transactions
33,775
public void checkCoinBaseHeight ( final int height ) throws VerificationException { checkArgument ( height >= Block . BLOCK_HEIGHT_GENESIS ) ; checkState ( isCoinBase ( ) ) ; final TransactionInput in = this . getInputs ( ) . get ( 0 ) ; final ScriptBuilder builder = new ScriptBuilder ( ) ; builder . number ( height ) ; final byte [ ] expected = builder . build ( ) . getProgram ( ) ; final byte [ ] actual = in . getScriptBytes ( ) ; if ( actual . length < expected . length ) { throw new VerificationException . CoinbaseHeightMismatch ( "Block height mismatch in coinbase." ) ; } for ( int scriptIdx = 0 ; scriptIdx < expected . length ; scriptIdx ++ ) { if ( actual [ scriptIdx ] != expected [ scriptIdx ] ) { throw new VerificationException . CoinbaseHeightMismatch ( "Block height mismatch in coinbase." ) ; } } }
Check block height is in coinbase input script for use after BIP 34 enforcement is enabled .
33,776
public Sha256Hash findWitnessCommitment ( ) { checkState ( isCoinBase ( ) ) ; for ( TransactionOutput out : Lists . reverse ( outputs ) ) { Script scriptPubKey = out . getScriptPubKey ( ) ; if ( ScriptPattern . isWitnessCommitment ( scriptPubKey ) ) return ScriptPattern . extractWitnessCommitmentHash ( scriptPubKey ) ; } return null ; }
Loops the outputs of a coinbase transaction to locate the witness commitment .
33,777
public Date estimateLockTime ( AbstractBlockChain chain ) { if ( lockTime < LOCKTIME_THRESHOLD ) return chain . estimateBlockTime ( ( int ) getLockTime ( ) ) ; else return new Date ( getLockTime ( ) * 1000 ) ; }
Returns either the lock time as a date if it was specified in seconds or an estimate based on the time in the current head block if it was specified as a block time .
33,778
public Coin getBalanceForServer ( Sha256Hash id ) { Coin balance = Coin . ZERO ; lock . lock ( ) ; try { Set < StoredClientChannel > setChannels = mapChannels . get ( id ) ; for ( StoredClientChannel channel : setChannels ) { synchronized ( channel ) { if ( channel . close != null ) continue ; balance = balance . add ( channel . valueToMe ) ; } } return balance ; } finally { lock . unlock ( ) ; } }
Returns the outstanding amount of money sent back to us for all channels to this server added together .
33,779
public long getSecondsUntilExpiry ( Sha256Hash id ) { lock . lock ( ) ; try { final Set < StoredClientChannel > setChannels = mapChannels . get ( id ) ; final long nowSeconds = Utils . currentTimeSeconds ( ) ; int earliestTime = Integer . MAX_VALUE ; for ( StoredClientChannel channel : setChannels ) { synchronized ( channel ) { if ( channel . expiryTimeSeconds ( ) > nowSeconds ) earliestTime = Math . min ( earliestTime , ( int ) channel . expiryTimeSeconds ( ) ) ; } } return earliestTime == Integer . MAX_VALUE ? 0 : earliestTime - nowSeconds ; } finally { lock . unlock ( ) ; } }
Returns the number of seconds from now until this servers next channel will expire or zero if no unexpired channels found .
33,780
public StoredClientChannel getChannel ( Sha256Hash id , Sha256Hash contractHash ) { lock . lock ( ) ; try { Set < StoredClientChannel > setChannels = mapChannels . get ( id ) ; for ( StoredClientChannel channel : setChannels ) { if ( channel . contract . getTxId ( ) . equals ( contractHash ) ) return channel ; } return null ; } finally { lock . unlock ( ) ; } }
Finds a channel with the given id and contract hash and returns it or returns null .
33,781
private TransactionBroadcaster getAnnouncePeerGroup ( ) { try { return announcePeerGroupFuture . get ( MAX_SECONDS_TO_WAIT_FOR_BROADCASTER_TO_BE_SET , TimeUnit . SECONDS ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } catch ( ExecutionException e ) { throw new RuntimeException ( e ) ; } catch ( TimeoutException e ) { String err = "Transaction broadcaster not set" ; log . error ( err ) ; throw new RuntimeException ( err , e ) ; } }
If the peer group has not been set for MAX_SECONDS_TO_WAIT_FOR_BROADCASTER_TO_BE_SET seconds then the programmer probably forgot to set it and we should throw exception .
33,782
public void saveNow ( ) throws IOException { if ( executor . isShutdown ( ) ) return ; Date lastBlockSeenTime = wallet . getLastBlockSeenTime ( ) ; log . info ( "Saving wallet; last seen block is height {}, date {}, hash {}" , wallet . getLastBlockSeenHeight ( ) , lastBlockSeenTime != null ? Utils . dateTimeFormat ( lastBlockSeenTime ) : "unknown" , wallet . getLastBlockSeenHash ( ) ) ; saveNowInternal ( ) ; }
Actually write the wallet file to disk using an atomic rename when possible . Runs on the current thread .
33,783
public void saveLater ( ) { if ( executor . isShutdown ( ) || savePending . getAndSet ( true ) ) return ; executor . schedule ( saver , delay , delayTimeUnit ) ; }
Queues up a save in the background . Useful for not very important wallet changes .
33,784
public void shutdownAndWait ( ) { executor . shutdown ( ) ; try { executor . awaitTermination ( Long . MAX_VALUE , TimeUnit . DAYS ) ; } catch ( InterruptedException x ) { throw new RuntimeException ( x ) ; } }
Shut down auto - saving .
33,785
public static KeyChainGroup createBasic ( NetworkParameters params ) { return new KeyChainGroup ( params , new BasicKeyChain ( ) , null , - 1 , - 1 , null , null ) ; }
Creates a keychain group with just a basic chain . No deterministic chains will be created automatically .
33,786
public final void mergeActiveKeyChains ( KeyChainGroup from , long keyRotationTimeSecs ) { checkArgument ( isEncrypted ( ) == from . isEncrypted ( ) , "encrypted and non-encrypted keychains cannot be mixed" ) ; for ( DeterministicKeyChain chain : from . getActiveKeyChains ( keyRotationTimeSecs ) ) addAndActivateHDChain ( chain ) ; }
Merge all active chains from the given keychain group into this keychain group .
33,787
public int importKeysAndEncrypt ( final List < ECKey > keys , KeyParameter aesKey ) { checkState ( keyCrypter != null , "Not encrypted" ) ; LinkedList < ECKey > encryptedKeys = Lists . newLinkedList ( ) ; for ( ECKey key : keys ) { if ( key . isEncrypted ( ) ) throw new IllegalArgumentException ( "Cannot provide already encrypted keys" ) ; encryptedKeys . add ( key . encrypt ( keyCrypter , aesKey ) ) ; } return importKeys ( encryptedKeys ) ; }
Imports the given unencrypted keys into the basic chain encrypting them along the way with the given key .
33,788
private void maybeMarkCurrentAddressAsUsed ( LegacyAddress address ) { checkArgument ( address . getOutputScriptType ( ) == ScriptType . P2SH ) ; for ( Map . Entry < KeyChain . KeyPurpose , Address > entry : currentAddresses . entrySet ( ) ) { if ( entry . getValue ( ) != null && entry . getValue ( ) . equals ( address ) ) { log . info ( "Marking P2SH address as used: {}" , address ) ; currentAddresses . put ( entry . getKey ( ) , freshAddress ( entry . getKey ( ) ) ) ; return ; } } }
If the given P2SH address is current advance it to a new one .
33,789
private void maybeMarkCurrentKeyAsUsed ( DeterministicKey key ) { for ( Map . Entry < KeyChain . KeyPurpose , DeterministicKey > entry : currentKeys . entrySet ( ) ) { if ( entry . getValue ( ) != null && entry . getValue ( ) . equals ( key ) ) { log . info ( "Marking key as used: {}" , key ) ; currentKeys . put ( entry . getKey ( ) , freshKey ( entry . getKey ( ) ) ) ; return ; } } }
If the given key is current advance the current key to a new one .
33,790
public int numKeys ( ) { int result = basic . numKeys ( ) ; if ( chains != null ) for ( DeterministicKeyChain chain : chains ) result += chain . numKeys ( ) ; return result ; }
Returns the number of keys managed by this group including the lookahead buffers .
33,791
public boolean removeImportedKey ( ECKey key ) { checkNotNull ( key ) ; checkArgument ( ! ( key instanceof DeterministicKey ) ) ; return basic . removeKey ( key ) ; }
Removes a key that was imported into the basic key chain . You cannot remove deterministic keys .
33,792
public static void setTargetTime ( Duration targetTime ) { ByteString bytes = ByteString . copyFrom ( Longs . toByteArray ( targetTime . toMillis ( ) ) ) ; Main . bitcoin . wallet ( ) . setTag ( TAG , bytes ) ; }
Writes the given time to the wallet as a tag so we can find it again in this class .
33,793
private int ascertainParentFingerprint ( DeterministicKey parentKey , int parentFingerprint ) throws IllegalArgumentException { if ( parentFingerprint != 0 ) { if ( parent != null ) checkArgument ( parent . getFingerprint ( ) == parentFingerprint , "parent fingerprint mismatch" , Integer . toHexString ( parent . getFingerprint ( ) ) , Integer . toHexString ( parentFingerprint ) ) ; return parentFingerprint ; } else return 0 ; }
Return the fingerprint of this key s parent as an int value or zero if this key is the root node of the key hierarchy . Raise an exception if the arguments are inconsistent . This method exists to avoid code repetition in the constructors .
33,794
public byte [ ] getPrivKeyBytes33 ( ) { byte [ ] bytes33 = new byte [ 33 ] ; byte [ ] priv = getPrivKeyBytes ( ) ; System . arraycopy ( priv , 0 , bytes33 , 33 - priv . length , priv . length ) ; return bytes33 ; }
Returns private key bytes padded with zeros to 33 bytes .
33,795
private BigInteger findOrDeriveEncryptedPrivateKey ( KeyCrypter keyCrypter , KeyParameter aesKey ) { if ( encryptedPrivateKey != null ) { byte [ ] decryptedKey = keyCrypter . decrypt ( encryptedPrivateKey , aesKey ) ; if ( decryptedKey . length != 32 ) throw new KeyCrypterException . InvalidCipherText ( "Decrypted key must be 32 bytes long, but is " + decryptedKey . length ) ; return new BigInteger ( 1 , decryptedKey ) ; } DeterministicKey cursor = parent ; while ( cursor != null ) { if ( cursor . encryptedPrivateKey != null ) break ; cursor = cursor . parent ; } if ( cursor == null ) throw new KeyCrypterException ( "Neither this key nor its parents have an encrypted private key" ) ; byte [ ] parentalPrivateKeyBytes = keyCrypter . decrypt ( cursor . encryptedPrivateKey , aesKey ) ; if ( parentalPrivateKeyBytes . length != 32 ) throw new KeyCrypterException . InvalidCipherText ( "Decrypted key must be 32 bytes long, but is " + parentalPrivateKeyBytes . length ) ; return derivePrivateKeyDownwards ( cursor , parentalPrivateKeyBytes ) ; }
to decrypt and re - derive .
33,796
public BigInteger getPrivKey ( ) { final BigInteger key = findOrDerivePrivateKey ( ) ; checkState ( key != null , "Private key bytes not available" ) ; return key ; }
Returns the private key of this deterministic key . Even if this object isn t storing the private key it can be re - derived by walking up to the parents if necessary and this is what will happen .
33,797
public static DeterministicKey deserializeB58 ( String base58 , NetworkParameters params ) { return deserializeB58 ( null , base58 , params ) ; }
Deserialize a base - 58 - encoded HD Key with no parent
33,798
public static List < File > getReferenceClientBlockFileList ( File blocksDir ) { checkArgument ( blocksDir . isDirectory ( ) , "%s is not a directory" , blocksDir ) ; List < File > list = new LinkedList < > ( ) ; for ( int i = 0 ; true ; i ++ ) { File file = new File ( blocksDir , String . format ( Locale . US , "blk%05d.dat" , i ) ) ; if ( ! file . exists ( ) ) break ; list . add ( file ) ; } return list ; }
Gets the list of files which contain blocks from Bitcoin Core .
33,799
public synchronized void checkState ( State requiredState ) throws IllegalStateException { if ( requiredState != currentState ) { throw new IllegalStateException ( String . format ( Locale . US , "Expected state %s, but in state %s" , requiredState , currentState ) ) ; } }
Checks that the machine is in the given state . Throws if it isn t .