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... |
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... | 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 )... | 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 {... | 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 ) ; BufferedBl... | 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 ) ; BufferedBloc... | 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 )... | 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 ( PAYM... | 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 . ... | 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 ( ) >= Netwo... | 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 ( By... | 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 = Byt... | 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 . leng... | 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 ) { by... | 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 . allocateDir... | 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 Arra... | 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 = ... | 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 n... | 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 ; cas... | 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 ) , timeoutSecon... | 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 . rea... | 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 ) { ... | 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 . fromS... | 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 i... | 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 ( redeemSc... | 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 . si... | 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 subScri... | 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 ... | 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 ) ; in... | 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_CHECKLOCKTIMEVERI... | 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 . encode... | 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 ; f... | 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 ... | 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 ) ; Trans... | 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_SCA... | 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 den... |
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 . getTxnHashAnd... | 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 )... | 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 ( ... | 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... | 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 , t... | 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... | 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 ... | 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... | 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 ) ... | 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 ) ;... | 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 (... | 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 ( ch... | 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... | 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 ) ; } ca... | 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 ( la... | 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... | 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 alread... | 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... | 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 ( entr... | 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 . getFin... | 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 ... | 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%0... | 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 . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.