idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
33,600
public < T > boolean registerDelegate ( String className , Delegate < T > delegate ) { return null == delegateMapping . putIfAbsent ( className , new HasDelegate < T > ( delegate , this ) ) ; }
Registers a delegate by specifying the class name . Returns true if registration is successful .
33,601
public boolean registerCollection ( CollectionSchema . MessageFactory factory ) { return null == collectionMapping . putIfAbsent ( factory . typeClass ( ) . getName ( ) , factory ) ; }
Registers a collection . Returns true if registration is successful .
33,602
public boolean registerMap ( MapSchema . MessageFactory factory ) { return null == mapMapping . putIfAbsent ( factory . typeClass ( ) . getName ( ) , factory ) ; }
Registers a map . Returns true if registration is successful .
33,603
public static Pipe newPipe ( byte [ ] data , int offset , int length , boolean numeric ) throws IOException { ArrayBufferInput in = new ArrayBufferInput ( data , offset , length ) ; return newPipe ( in , numeric ) ; }
Creates a msgpack pipe from a byte array .
33,604
public int readRawVarint32 ( ) throws IOException { byte tmp = buffer [ offset ++ ] ; if ( tmp >= 0 ) { return tmp ; } int result = tmp & 0x7f ; if ( ( tmp = buffer [ offset ++ ] ) >= 0 ) { result |= tmp << 7 ; } else { result |= ( tmp & 0x7f ) << 7 ; if ( ( tmp = buffer [ offset ++ ] ) >= 0 ) { result |= tmp << 14 ; }...
Reads a var int 32 from the internal byte buffer .
33,605
public static void writeInt16LE ( final int value , final byte [ ] buffer , int offset ) { buffer [ offset ++ ] = ( byte ) value ; buffer [ offset ] = ( byte ) ( ( value >>> 8 ) & 0xFF ) ; }
Writes the 16 - bit int into the buffer starting with the least significant byte .
33,606
public static void writeInt32 ( final int value , final byte [ ] buffer , int offset ) { buffer [ offset ++ ] = ( byte ) ( ( value >>> 24 ) & 0xFF ) ; buffer [ offset ++ ] = ( byte ) ( ( value >>> 16 ) & 0xFF ) ; buffer [ offset ++ ] = ( byte ) ( ( value >>> 8 ) & 0xFF ) ; buffer [ offset ] = ( byte ) ( ( value >>> 0 )...
Writes the 32 - bit int into the buffer starting with the most significant byte .
33,607
public static void writeInt32LE ( final int value , final byte [ ] buffer , int offset ) { buffer [ offset ++ ] = ( byte ) ( ( value >>> 0 ) & 0xFF ) ; buffer [ offset ++ ] = ( byte ) ( ( value >>> 8 ) & 0xFF ) ; buffer [ offset ++ ] = ( byte ) ( ( value >>> 16 ) & 0xFF ) ; buffer [ offset ] = ( byte ) ( ( value >>> 24...
Writes the 32 - bit int into the buffer starting with the least significant byte .
33,608
public static void writeInt64 ( final long value , final byte [ ] buffer , int offset ) { buffer [ offset ++ ] = ( byte ) ( value >>> 56 ) ; buffer [ offset ++ ] = ( byte ) ( value >>> 48 ) ; buffer [ offset ++ ] = ( byte ) ( value >>> 40 ) ; buffer [ offset ++ ] = ( byte ) ( value >>> 32 ) ; buffer [ offset ++ ] = ( b...
Writes the 64 - bit int into the buffer starting with the most significant byte .
33,609
public static void writeInt64LE ( final long value , final byte [ ] buffer , int offset ) { buffer [ offset ++ ] = ( byte ) ( value >>> 0 ) ; buffer [ offset ++ ] = ( byte ) ( value >>> 8 ) ; buffer [ offset ++ ] = ( byte ) ( value >>> 16 ) ; buffer [ offset ++ ] = ( byte ) ( value >>> 24 ) ; buffer [ offset ++ ] = ( b...
Writes the 64 - bit int into the buffer starting with the least significant byte .
33,610
public MsgpackParser use ( MsgpackParser newParser ) { MsgpackParser old = this . parser ; this . parser = newParser ; return old ; }
Use another parser in msgpack input
33,611
HasName findFullyQualifiedObject ( String fullyQualifiedName ) { Message m = fullyQualifiedMessages . get ( fullyQualifiedName ) ; if ( m != null ) return m ; EnumGroup eg = fullyQualifiedEnumGroups . get ( fullyQualifiedName ) ; if ( eg != null ) return eg ; for ( Proto proto : getImportedProtos ( ) ) { HasName import...
Returns a Message or EnumGroup given its fully qualified name
33,612
public static < T > Schema < T > getSchema ( Class < T > typeClass , IdStrategy strategy ) { return strategy . getSchemaWrapper ( typeClass , true ) . getSchema ( ) ; }
Gets the schema that was either registered or lazily initialized at runtime .
33,613
static < T > HasSchema < T > getSchemaWrapper ( Class < T > typeClass , IdStrategy strategy ) { return strategy . getSchemaWrapper ( typeClass , true ) ; }
Returns the schema wrapper .
33,614
public static < T > RuntimeSchema < T > createFrom ( Class < T > typeClass , IdStrategy strategy ) { return createFrom ( typeClass , NO_EXCLUSIONS , strategy ) ; }
Generates a schema from the given class .
33,615
public static Pipe newPipe ( byte [ ] data , int offset , int length ) throws IOException { return newPipe ( new ByteArrayInputStream ( data , offset , length ) ) ; }
Creates an xml pipe from a byte array .
33,616
public static CodedInput newInstance ( final byte [ ] buf , final int off , final int len ) { return new CodedInput ( buf , off , len , false ) ; }
Create a new CodedInput wrapping the given byte array slice .
33,617
public boolean skipField ( final int tag ) throws IOException { switch ( WireFormat . getTagWireType ( tag ) ) { case WireFormat . WIRETYPE_VARINT : readInt32 ( ) ; return true ; case WireFormat . WIRETYPE_FIXED64 : readRawLittleEndian64 ( ) ; return true ; case WireFormat . WIRETYPE_LENGTH_DELIMITED : skipRawBytes ( r...
Reads and discards a single field given its tag value .
33,618
public int readRawLittleEndian32 ( ) throws IOException { final byte b1 = readRawByte ( ) ; final byte b2 = readRawByte ( ) ; final byte b3 = readRawByte ( ) ; final byte b4 = readRawByte ( ) ; return ( ( ( int ) b1 & 0xff ) ) | ( ( ( int ) b2 & 0xff ) << 8 ) | ( ( ( int ) b3 & 0xff ) << 16 ) | ( ( ( int ) b4 & 0xff ) ...
Read a 32 - bit little - endian integer from the stream .
33,619
public long readRawLittleEndian64 ( ) throws IOException { final byte b1 = readRawByte ( ) ; final byte b2 = readRawByte ( ) ; final byte b3 = readRawByte ( ) ; final byte b4 = readRawByte ( ) ; final byte b5 = readRawByte ( ) ; final byte b6 = readRawByte ( ) ; final byte b7 = readRawByte ( ) ; final byte b8 = readRaw...
Read a 64 - bit little - endian integer from the stream .
33,620
public void reset ( ) { this . bufferSize = 0 ; this . bufferPos = 0 ; this . bufferSizeAfterLimit = 0 ; this . currentLimit = Integer . MAX_VALUE ; this . lastTag = 0 ; this . packedLimit = 0 ; this . sizeLimit = DEFAULT_SIZE_LIMIT ; resetSizeCounter ( ) ; }
Resets the buffer position and limit to re - use this CodedInput object .
33,621
public byte [ ] readRawBytes ( final int size ) throws IOException { if ( size < 0 ) { throw ProtobufException . negativeSize ( ) ; } if ( totalBytesRetired + bufferPos + size > currentLimit ) { skipRawBytes ( currentLimit - totalBytesRetired - bufferPos ) ; throw ProtobufException . truncatedMessage ( ) ; } if ( size ...
Read a fixed size of bytes from the input .
33,622
public static int parseInt ( final byte [ ] buffer , final int start , final int length , final int radix ) throws NumberFormatException { if ( length == 0 ) throw new NumberFormatException ( STRING . deser ( buffer , start , length ) ) ; if ( buffer [ start ] == '-' ) { if ( length == 1 ) throw new NumberFormatExcepti...
Parse an ascii int from a raw buffer .
33,623
private static long remainder ( long dividend , long divisor ) { if ( divisor < 0 ) { if ( compareUnsigned ( dividend , divisor ) < 0 ) { return dividend ; } else { return dividend - divisor ; } } if ( dividend >= 0 ) { return dividend % divisor ; } long quotient = ( ( dividend >>> 1 ) / divisor ) << 1 ; long rem = div...
Returns dividend % divisor where the dividend and divisor are treated as unsigned 64 - bit quantities .
33,624
protected void onAttachedToWindow ( ) { super . onAttachedToWindow ( ) ; if ( LOG_ATTACH_DETACH ) { Log . d ( TAG , "onAttachedToWindow reattach =" + mDetached ) ; } if ( mDetached && ( mRenderer != null ) ) { int renderMode = RENDERMODE_CONTINUOUSLY ; if ( mGLThread != null ) { renderMode = mGLThread . getRenderMode (...
This method is used as part of the View class and is not normally called or subclassed by clients of GLSurfaceView .
33,625
protected void onDetachedFromWindow ( ) { if ( LOG_ATTACH_DETACH ) { Log . d ( TAG , "onDetachedFromWindow" ) ; } if ( mGLThread != null ) { mGLThread . requestExitAndWait ( ) ; } mDetached = true ; super . onDetachedFromWindow ( ) ; }
This method is used as part of the View class and is not normally called or subclassed by clients of GLSurfaceView . Must not be called before a renderer has been set .
33,626
private static OkHttpClient getNewOkHttpClient ( boolean enableTLS ) { OkHttpClient . Builder client = new OkHttpClient . Builder ( ) . connectTimeout ( DEFAULT_CONNECT_TIMEOUT , TimeUnit . SECONDS ) . readTimeout ( DEFAULT_READ_TIMEOUT , TimeUnit . SECONDS ) ; if ( enableTLS ) { client = enableTls12 ( client ) ; } ret...
Creates an OkHttpClient optionally enabling TLS
33,627
private static OkHttpClient . Builder enableTls12 ( OkHttpClient . Builder client ) { try { TrustManagerFactory trustManagerFactory = TrustManagerFactory . getInstance ( TrustManagerFactory . getDefaultAlgorithm ( ) ) ; trustManagerFactory . init ( ( KeyStore ) null ) ; TrustManager [ ] trustManagers = trustManagerFact...
Enable TLS on the OKHttp builder by setting a custom SocketFactory
33,628
public void start ( ) { if ( mEgl == null ) { mEgl = ( EGL10 ) EGLContext . getEGL ( ) ; } else { } if ( mEglDisplay == null ) { mEglDisplay = mEgl . eglGetDisplay ( EGL10 . EGL_DEFAULT_DISPLAY ) ; } else { } if ( mEglConfig == null ) { int [ ] version = new int [ 2 ] ; mEgl . eglInitialize ( mEglDisplay , version ) ; ...
Initialize EGL for a given configuration spec .
33,629
public void queueEvent ( Runnable r ) { synchronized ( this ) { mEventQueue . add ( r ) ; synchronized ( sGLThreadManager ) { mEventsWaiting = true ; sGLThreadManager . notifyAll ( ) ; } } }
Queue an event to be run on the GL rendering thread .
33,630
public static UserCommand deserialize ( String serialized ) { int id = - 1 ; if ( TextUtils . isEmpty ( serialized ) ) { return new UserCommand ( id , null ) ; } String [ ] arr = serialized . split ( ":" , 2 ) ; try { id = Integer . parseInt ( arr [ 0 ] ) ; } catch ( NumberFormatException ignored ) { } String title = n...
Deserializes a user command from the given string .
33,631
private static HashMap < String , String > buildAllArtworkColumnProjectionMap ( ) { final HashMap < String , String > allColumnProjectionMap = new HashMap < > ( ) ; allColumnProjectionMap . put ( BaseColumns . _ID , BaseColumns . _ID ) ; allColumnProjectionMap . put ( ProviderContract . Artwork . TOKEN , ProviderContra...
Creates and initializes a column project for all columns for artwork
33,632
protected final void removeAllUserCommands ( ) { mCurrentState . setUserCommands ( ( int [ ] ) null ) ; mServiceHandler . removeCallbacks ( mPublishStateRunnable ) ; mServiceHandler . post ( mPublishStateRunnable ) ; }
Clears the list of available user commands .
33,633
public boolean checkSignature ( PaymentNotification notification ) { SortedMap < String , Object > notificationMap = JsonMapper . nonEmptyMapper ( ) . getMapper ( ) . convertValue ( notification , SortedMap . class ) ; notificationMap . putAll ( notification . getOthers ( ) ) ; notificationMap . remove ( "sign" ) ; ret...
check if sign is valid
33,634
public String next ( ) { if ( entry == null ) return null ; entry = entry . next ; return entry . element ; }
Returns the next zone from the set which should get the request .
33,635
public String next ( String ignoreZone ) { if ( entry == null ) return null ; entry = entry . next ; if ( entry . element . equals ( ignoreZone ) ) { return entry . next . element ; } else { return entry . element ; } }
Returns the next zone from the set excluding the given zone which should get the request .
33,636
protected String getSocketAddressForNode ( MemcachedNode node ) { String result = socketAddresses . get ( node ) ; if ( result == null ) { final SocketAddress socketAddress = node . getSocketAddress ( ) ; if ( socketAddress instanceof InetSocketAddress ) { final InetSocketAddress isa = ( InetSocketAddress ) socketAddre...
Returns the socket address of a given MemcachedNode .
33,637
public final synchronized void initEVCache ( String app ) { if ( app == null || ( app = app . trim ( ) ) . length ( ) == 0 ) throw new IllegalArgumentException ( "param app name null or space" ) ; final String APP = getAppName ( app ) ; if ( poolMap . containsKey ( APP ) ) return ; final EVCacheNodeList provider ; if (...
Will init the given EVCache app call . If one is already initialized for the given app method returns without doing anything .
33,638
public EVCacheClientPool getEVCacheClientPool ( String _app ) { final String app = getAppName ( _app ) ; final EVCacheClientPool evcacheClientPool = poolMap . get ( app ) ; if ( evcacheClientPool != null ) return evcacheClientPool ; initEVCache ( app ) ; return poolMap . get ( app ) ; }
Given the appName get the EVCacheClientPool . If the app is already created then will return the existing instance . If not one will be created and returned .
33,639
private void updateMemcachedReadInstancesByZone ( ) { for ( ServerGroup serverGroup : memcachedInstancesByServerGroup . keySet ( ) ) { final BooleanProperty isZoneInWriteOnlyMode = writeOnlyFastPropertyMap . get ( serverGroup ) ; if ( isZoneInWriteOnlyMode . get ( ) . booleanValue ( ) ) { if ( memcachedReadInstancesByS...
back to the read map .
33,640
public Map < ServerGroup , EVCacheServerGroupConfig > discoverInstances ( String appName ) throws IOException { final String propertyName = appName + "-NODES" ; final String nodeListString = EVCacheConfig . getInstance ( ) . getDynamicStringProperty ( propertyName , "" ) . get ( ) ; if ( log . isDebugEnabled ( ) ) log ...
Pass a System Property of format
33,641
public void setKey ( String key , String value , int timeToLive ) throws Exception { try { Future < Boolean > [ ] _future = evCache . set ( key , value , timeToLive ) ; for ( Future < Boolean > f : _future ) { boolean didSucceed = f . get ( ) ; if ( verboseMode ) { System . out . println ( "per-shard set success code f...
Set a key in the cache .
33,642
public String getKey ( String key ) { try { String _response = evCache . < String > get ( key ) ; return _response ; } catch ( Exception e ) { e . printStackTrace ( ) ; return null ; } }
Get the data for a key from the cache . Returns null if the key could not be retrieved whether due to a cache miss or errors .
33,643
public static void main ( String [ ] args ) { verboseMode = ( "true" . equals ( System . getenv ( "EVCACHE_SAMPLE_VERBOSE" ) ) ) ; if ( verboseMode ) { System . out . println ( "To run this sample app without using Gradle:" ) ; System . out . println ( "java -cp " + System . getProperty ( "java.class.path" ) + " com.ne...
Main Program which does some simple sets and gets .
33,644
public Map < String , CachedData > getAllChunks ( String key ) throws EVCacheReadQueueException , EVCacheException , Exception { try { final ChunkDetails < Object > cd = getChunkDetails ( key ) ; if ( log . isDebugEnabled ( ) ) log . debug ( "Chunkdetails " + cd ) ; if ( cd == null ) return null ; if ( ! cd . isChunked...
Retrieves all the chunks as is . This is mainly used for debugging .
33,645
public boolean isBloomFilteringSupported ( ) { if ( clientVersion >= params . getProtocolVersionNum ( NetworkParameters . ProtocolVersion . BLOOM_FILTER ) && clientVersion < params . getProtocolVersionNum ( NetworkParameters . ProtocolVersion . BLOOM_FILTER_BIP111 ) ) return true ; if ( ( localServices & NODE_BLOOM ) =...
Returns true if the peer supports bloom filtering according to BIP37 and BIP111 .
33,646
public Fiat coinToFiat ( Coin convertCoin ) { final BigInteger converted = BigInteger . valueOf ( convertCoin . value ) . multiply ( BigInteger . valueOf ( fiat . value ) ) . divide ( BigInteger . valueOf ( coin . value ) ) ; if ( converted . compareTo ( BigInteger . valueOf ( Long . MAX_VALUE ) ) > 0 || converted . co...
Convert a coin amount to a fiat amount using this exchange rate .
33,647
public Coin fiatToCoin ( Fiat convertFiat ) { checkArgument ( convertFiat . currencyCode . equals ( fiat . currencyCode ) , "Currency mismatch: %s vs %s" , convertFiat . currencyCode , fiat . currencyCode ) ; final BigInteger converted = BigInteger . valueOf ( convertFiat . value ) . multiply ( BigInteger . valueOf ( c...
Convert a fiat amount to a coin amount using this exchange rate .
33,648
public static BIP38PrivateKey fromBase58 ( NetworkParameters params , String base58 ) throws AddressFormatException { byte [ ] versionAndDataBytes = Base58 . decodeChecked ( base58 ) ; int version = versionAndDataBytes [ 0 ] & 0xFF ; byte [ ] bytes = Arrays . copyOfRange ( versionAndDataBytes , 1 , versionAndDataBytes ...
Construct a password - protected private key from its Base58 representation .
33,649
public Script freshOutputScript ( KeyPurpose purpose ) { DeterministicKey followedKey = getKey ( purpose ) ; ImmutableList . Builder < ECKey > keys = ImmutableList . < ECKey > builder ( ) . add ( followedKey ) ; for ( DeterministicKeyChain keyChain : followingKeyChains ) { DeterministicKey followingKey = keyChain . get...
Create a new married key and return the matching output script
33,650
public RedeemData getRedeemData ( DeterministicKey followedKey ) { List < ECKey > marriedKeys = getMarriedKeysWithFollowed ( followedKey ) ; Script redeemScript = ScriptBuilder . createRedeemScript ( sigsRequiredToSpend , marriedKeys ) ; return RedeemData . of ( marriedKeys , redeemScript ) ; }
Get the redeem data for a key in this married chain
33,651
public Protos . Wallet walletToProto ( Wallet wallet ) { Protos . Wallet . Builder walletBuilder = Protos . Wallet . newBuilder ( ) ; walletBuilder . setNetworkIdentifier ( wallet . getNetworkParameters ( ) . getId ( ) ) ; if ( wallet . getDescription ( ) != null ) { walletBuilder . setDescription ( wallet . getDescrip...
Converts the given wallet to the object representation of the protocol buffers . This can be modified or additional data fields set before serialization takes place .
33,652
public static boolean isWallet ( InputStream is ) { try { final CodedInputStream cis = CodedInputStream . newInstance ( is ) ; final int tag = cis . readTag ( ) ; final int field = WireFormat . getTagFieldNumber ( tag ) ; if ( field != 1 ) return false ; final String network = cis . readString ( ) ; return NetworkParam...
Cheap test to see if input stream is a wallet . This checks for a magic value at the beginning of the stream .
33,653
protected List < String > getCompatibilitySQL ( ) { List < String > sqlStatements = new ArrayList < > ( ) ; sqlStatements . add ( SELECT_COMPATIBILITY_COINBASE_SQL ) ; return sqlStatements ; }
Get the SQL statements to check if the database is compatible .
33,654
private void initFromDatabase ( ) throws SQLException , BlockStoreException { PreparedStatement ps = conn . get ( ) . prepareStatement ( getSelectSettingsSQL ( ) ) ; ResultSet rs ; ps . setString ( 1 , CHAIN_HEAD_SETTING ) ; rs = ps . executeQuery ( ) ; if ( ! rs . next ( ) ) { throw new BlockStoreException ( "corrupt ...
Initialise the store state from the database .
33,655
public void resetStore ( ) throws BlockStoreException { maybeConnect ( ) ; try { deleteStore ( ) ; createTables ( ) ; initFromDatabase ( ) ; } catch ( SQLException ex ) { throw new RuntimeException ( ex ) ; } }
Resets the store by deleting the contents of the tables and reinitialising them .
33,656
public void deleteStore ( ) throws BlockStoreException { maybeConnect ( ) ; try { Statement s = conn . get ( ) . createStatement ( ) ; for ( String sql : getDropTablesSQL ( ) ) { s . execute ( sql ) ; } s . close ( ) ; } catch ( SQLException ex ) { throw new RuntimeException ( ex ) ; } }
Deletes the store by deleting the tables within the database .
33,657
public BigInteger calculateBalanceForAddress ( Address address ) throws BlockStoreException { maybeConnect ( ) ; PreparedStatement s = null ; try { s = conn . get ( ) . prepareStatement ( getBalanceSelectSQL ( ) ) ; s . setString ( 1 , address . toString ( ) ) ; ResultSet rs = s . executeQuery ( ) ; BigInteger balance ...
Calculate the balance for a coinbase to - address or p2sh address .
33,658
public DeterministicKey get ( List < ChildNumber > path , boolean relativePath , boolean create ) { ImmutableList < ChildNumber > absolutePath = relativePath ? ImmutableList . < ChildNumber > builder ( ) . addAll ( rootPath ) . addAll ( path ) . build ( ) : ImmutableList . copyOf ( path ) ; if ( ! keys . containsKey ( ...
Returns a key for the given path optionally creating it .
33,659
public static String encodeChecked ( int version , byte [ ] payload ) { if ( version < 0 || version > 255 ) throw new IllegalArgumentException ( "Version not in range." ) ; byte [ ] addressBytes = new byte [ 1 + payload . length + 4 ] ; addressBytes [ 0 ] = ( byte ) version ; System . arraycopy ( payload , 0 , addressB...
Encodes the given version and bytes as a base58 string . A checksum is appended .
33,660
public static byte [ ] decode ( String input ) throws AddressFormatException { if ( input . length ( ) == 0 ) { return new byte [ 0 ] ; } byte [ ] input58 = new byte [ input . length ( ) ] ; for ( int i = 0 ; i < input . length ( ) ; ++ i ) { char c = input . charAt ( i ) ; int digit = c < 128 ? INDEXES [ c ] : - 1 ; i...
Decodes the given base58 string into the original data bytes .
33,661
public static byte [ ] decodeChecked ( String input ) throws AddressFormatException { byte [ ] decoded = decode ( input ) ; if ( decoded . length < 4 ) throw new AddressFormatException . InvalidDataLength ( "Input too short: " + decoded . length ) ; byte [ ] data = Arrays . copyOfRange ( decoded , 0 , decoded . length ...
Decodes the given base58 string into the original data bytes using the checksum in the last 4 bytes of the decoded data to verify that the rest are correct . The checksum is removed from the returned data .
33,662
private static byte divmod ( byte [ ] number , int firstDigit , int base , int divisor ) { int remainder = 0 ; for ( int i = firstDigit ; i < number . length ; i ++ ) { int digit = ( int ) number [ i ] & 0xFF ; int temp = remainder * base + digit ; number [ i ] = ( byte ) ( temp / divisor ) ; remainder = temp % divisor...
Divides a number represented as an array of bytes each containing a single digit in the specified base by the given divisor . The given number is modified in - place to contain the quotient and the return value is the remainder .
33,663
private static void setup ( ) throws BlockStoreException { if ( store != null ) return ; boolean reset = ! chainFileName . exists ( ) ; if ( reset ) { System . out . println ( "Chain file is missing so resetting the wallet." ) ; reset ( ) ; } if ( mode == ValidationMode . SPV ) { store = new SPVBlockStore ( params , ch...
Sets up all objects needed for network communication but does not bring up the peers .
33,664
private static byte [ ] parseAsHexOrBase58 ( String data ) { try { return Utils . HEX . decode ( data ) ; } catch ( Exception e ) { try { return Base58 . decodeChecked ( data ) ; } catch ( AddressFormatException e1 ) { return null ; } } }
Attempts to parse the given string as arbitrary - length hex or base58 and then return the results or null if neither parse was successful .
33,665
public void trackFailure ( ) { retryTime = Utils . currentTimeMillis ( ) + ( long ) backoff ; backoff = Math . min ( backoff * params . multiplier , params . maximum ) ; }
Track a failure - multiply the back off interval by the multiplier
33,666
private static int polymod ( final byte [ ] values ) { int c = 1 ; for ( byte v_i : values ) { int c0 = ( c >>> 25 ) & 0xff ; c = ( ( c & 0x1ffffff ) << 5 ) ^ ( v_i & 0xff ) ; if ( ( c0 & 1 ) != 0 ) c ^= 0x3b6a57b2 ; if ( ( c0 & 2 ) != 0 ) c ^= 0x26508e6d ; if ( ( c0 & 4 ) != 0 ) c ^= 0x1ea119fa ; if ( ( c0 & 8 ) != 0 ...
Find the polynomial with value coefficients mod the generator as 30 - bit .
33,667
private static byte [ ] expandHrp ( final String hrp ) { int hrpLength = hrp . length ( ) ; byte ret [ ] = new byte [ hrpLength * 2 + 1 ] ; for ( int i = 0 ; i < hrpLength ; ++ i ) { int c = hrp . charAt ( i ) & 0x7f ; ret [ i ] = ( byte ) ( ( c >>> 5 ) & 0x07 ) ; ret [ i + hrpLength + 1 ] = ( byte ) ( c & 0x1f ) ; } r...
Expand a HRP for use in checksum computation .
33,668
private static boolean verifyChecksum ( final String hrp , final byte [ ] values ) { byte [ ] hrpExpanded = expandHrp ( hrp ) ; byte [ ] combined = new byte [ hrpExpanded . length + values . length ] ; System . arraycopy ( hrpExpanded , 0 , combined , 0 , hrpExpanded . length ) ; System . arraycopy ( values , 0 , combi...
Verify a checksum .
33,669
private static byte [ ] createChecksum ( final String hrp , final byte [ ] values ) { byte [ ] hrpExpanded = expandHrp ( hrp ) ; byte [ ] enc = new byte [ hrpExpanded . length + values . length + 6 ] ; System . arraycopy ( hrpExpanded , 0 , enc , 0 , hrpExpanded . length ) ; System . arraycopy ( values , 0 , enc , hrpE...
Create a checksum .
33,670
public static String encode ( String hrp , final byte [ ] values ) { checkArgument ( hrp . length ( ) >= 1 , "Human-readable part is too short" ) ; checkArgument ( hrp . length ( ) <= 83 , "Human-readable part is too long" ) ; hrp = hrp . toLowerCase ( Locale . ROOT ) ; byte [ ] checksum = createChecksum ( hrp , values...
Encode a Bech32 string .
33,671
public static Bech32Data decode ( final String str ) throws AddressFormatException { boolean lower = false , upper = false ; if ( str . length ( ) < 8 ) throw new AddressFormatException . InvalidDataLength ( "Input too short: " + str . length ( ) ) ; if ( str . length ( ) > 90 ) throw new AddressFormatException . Inval...
Decode a Bech32 string .
33,672
public boolean isCoinBase ( ) { return outpoint . getHash ( ) . equals ( Sha256Hash . ZERO_HASH ) && ( outpoint . getIndex ( ) & 0xFFFFFFFFL ) == 0xFFFFFFFFL ; }
Coinbase transactions have special inputs with hashes of zero . If this is such an input returns true .
33,673
public void setScriptSig ( Script scriptSig ) { this . scriptSig = new WeakReference < > ( checkNotNull ( scriptSig ) ) ; setScriptBytes ( scriptSig . getProgram ( ) ) ; }
Set the given program as the scriptSig that is supposed to satisfy the connected output script .
33,674
public ConnectionResult connect ( Map < Sha256Hash , Transaction > transactions , ConnectMode mode ) { Transaction tx = transactions . get ( outpoint . getHash ( ) ) ; if ( tx == null ) { return TransactionInput . ConnectionResult . NO_SUCH_TX ; } return connect ( tx , mode ) ; }
Connects this input to the relevant output of the referenced transaction if it s in the given map . Connecting means updating the internal pointers and spent flags . If the mode is to ABORT_ON_CONFLICT then the spent output won t be changed but the outpoint . fromTx pointer will still be updated .
33,675
public ConnectionResult connect ( Transaction transaction , ConnectMode mode ) { if ( ! transaction . getTxId ( ) . equals ( outpoint . getHash ( ) ) ) return ConnectionResult . NO_SUCH_TX ; checkElementIndex ( ( int ) outpoint . getIndex ( ) , transaction . getOutputs ( ) . size ( ) , "Corrupt transaction" ) ; Transac...
Connects this input to the relevant output of the referenced transaction . Connecting means updating the internal pointers and spent flags . If the mode is to ABORT_ON_CONFLICT then the spent output won t be changed but the outpoint . fromTx pointer will still be updated .
33,676
public boolean disconnect ( ) { TransactionOutput connectedOutput ; if ( outpoint . fromTx != null ) { connectedOutput = outpoint . fromTx . getOutput ( ( int ) outpoint . getIndex ( ) ) ; outpoint . fromTx = null ; } else if ( outpoint . connectedOutput != null ) { connectedOutput = outpoint . connectedOutput ; outpoi...
If this input is connected check the output is connected back to this input and release it if so making it spendable once again .
33,677
public void verify ( ) throws VerificationException { final Transaction fromTx = getOutpoint ( ) . fromTx ; long spendingIndex = getOutpoint ( ) . getIndex ( ) ; checkNotNull ( fromTx , "Not connected" ) ; final TransactionOutput output = fromTx . getOutput ( ( int ) spendingIndex ) ; verify ( output ) ; }
For a connected transaction runs the script against the connected pubkey and verifies they are correct .
33,678
public void verify ( TransactionOutput output ) throws VerificationException { if ( output . parent != null ) { if ( ! getOutpoint ( ) . getHash ( ) . equals ( output . getParentTransaction ( ) . getTxId ( ) ) ) throw new VerificationException ( "This input does not refer to the tx containing the output." ) ; if ( getO...
Verifies that this input can spend the given output . Note that this input must be a part of a transaction . Also note that the consistency of the outpoint will be checked even if this input has not been connected .
33,679
public String getMnemonicString ( ) { return mnemonicCode != null ? Utils . SPACE_JOINER . join ( mnemonicCode ) : null ; }
Get the mnemonic code as string or null if unknown .
33,680
public TransactionOutput getConnectedOutput ( ) { if ( fromTx != null ) { return fromTx . getOutputs ( ) . get ( ( int ) index ) ; } else if ( connectedOutput != null ) { return connectedOutput ; } return null ; }
An outpoint is a part of a transaction input that points to the output of another transaction . If we have both sides in memory and they have been linked together this returns a pointer to the connected output or null if there is no such connection .
33,681
public RedeemData getConnectedRedeemData ( KeyBag keyBag ) throws ScriptException { TransactionOutput connectedOutput = getConnectedOutput ( ) ; checkNotNull ( connectedOutput , "Input is not connected so cannot retrieve key" ) ; Script connectedScript = connectedOutput . getScriptPubKey ( ) ; if ( ScriptPattern . isP2...
Returns the RedeemData identified in the connected output for either P2PKH P2WPKH P2PK or P2SH scripts . If the script forms cannot be understood throws ScriptException .
33,682
public void setMaxConnections ( int maxConnections ) { int adjustment ; lock . lock ( ) ; try { this . maxConnections = maxConnections ; if ( ! isRunning ( ) ) return ; } finally { lock . unlock ( ) ; } adjustment = maxConnections - channels . getConnectedClientCount ( ) ; if ( adjustment > 0 ) triggerConnections ( ) ;...
Adjusts the desired number of connections that we will create to peers . Note that if there are already peers open and the new value is lower than the current number of peers those connections will be terminated . Likewise if there aren t enough current connections to meet the new requested max size some will be added ...
33,683
private void updateVersionMessageRelayTxesBeforeFilter ( VersionMessage ver ) { lock . lock ( ) ; try { boolean spvMode = chain != null && ! chain . shouldVerifyTransactions ( ) ; boolean willSendFilter = spvMode && peerFilterProviders . size ( ) > 0 && vBloomFilteringEnabled ; ver . relayTxesBeforeFilter = ! willSendF...
Updates the relayTxesBeforeFilter flag of ver
33,684
public void addAddress ( PeerAddress peerAddress ) { int newMax ; lock . lock ( ) ; try { if ( addInactive ( peerAddress ) ) { newMax = getMaxConnections ( ) + 1 ; setMaxConnections ( newMax ) ; } } finally { lock . unlock ( ) ; } }
Add an address to the list of potential peers to connect to . It won t necessarily be used unless there s a need to build new connections to reach the max connection count .
33,685
private boolean addInactive ( PeerAddress peerAddress ) { lock . lock ( ) ; try { if ( backoffMap . containsKey ( peerAddress ) ) return false ; backoffMap . put ( peerAddress , new ExponentialBackoff ( peerBackoffParams ) ) ; inactives . offer ( peerAddress ) ; return true ; } finally { lock . unlock ( ) ; } }
Returns true if it was added false if it was already there .
33,686
public void setRequiredServices ( long requiredServices ) { lock . lock ( ) ; try { this . requiredServices = requiredServices ; peerDiscoverers . clear ( ) ; addPeerDiscovery ( MultiplexingDiscovery . forServices ( params , requiredServices ) ) ; } finally { lock . unlock ( ) ; } }
Convenience for connecting only to peers that can serve specific services . It will configure suitable peer discoveries .
33,687
public void addPeerDiscovery ( PeerDiscovery peerDiscovery ) { lock . lock ( ) ; try { if ( getMaxConnections ( ) == 0 ) setMaxConnections ( DEFAULT_CONNECTIONS ) ; peerDiscoverers . add ( peerDiscovery ) ; } finally { lock . unlock ( ) ; } }
Add addresses from a discovery source to the list of potential peers to connect to . If max connections has not been configured or set to zero then it s set to the default at this point .
33,688
protected int discoverPeers ( ) { checkState ( ! lock . isHeldByCurrentThread ( ) ) ; int maxPeersToDiscoverCount = this . vMaxPeersToDiscoverCount ; long peerDiscoveryTimeoutMillis = this . vPeerDiscoveryTimeoutMillis ; final Stopwatch watch = Stopwatch . createStarted ( ) ; final List < PeerAddress > addressList = Li...
Returns number of discovered peers .
33,689
public ListenableFuture startAsync ( ) { if ( chain == null ) { log . warn ( "Starting up with no attached block chain. Did you forget to pass one to the constructor?" ) ; } checkState ( ! vUsedUp , "Cannot start a peer group twice" ) ; vRunning = true ; vUsedUp = true ; executorStartupLatch . countDown ( ) ; return ex...
Starts the PeerGroup and begins network activity .
33,690
public void stop ( ) { try { Stopwatch watch = Stopwatch . createStarted ( ) ; stopAsync ( ) ; log . info ( "Awaiting PeerGroup shutdown ..." ) ; executor . awaitTermination ( Long . MAX_VALUE , TimeUnit . SECONDS ) ; log . info ( "... took {}" , watch ) ; } catch ( InterruptedException e ) { throw new RuntimeException...
Does a blocking stop
33,691
public void removeWallet ( Wallet wallet ) { wallets . remove ( checkNotNull ( wallet ) ) ; peerFilterProviders . remove ( wallet ) ; wallet . removeCoinsReceivedEventListener ( walletCoinsReceivedEventListener ) ; wallet . removeKeyChainEventListener ( walletKeyEventListener ) ; wallet . removeScriptsChangeEventListen...
Unlinks the given wallet so it no longer receives broadcast transactions or has its transactions announced .
33,692
public Peer connectToLocalHost ( ) { lock . lock ( ) ; try { final PeerAddress localhost = PeerAddress . localhost ( params ) ; backoffMap . put ( localhost , new ExponentialBackoff ( peerBackoffParams ) ) ; return connectTo ( localhost , true , vConnectTimeoutMillis ) ; } finally { lock . unlock ( ) ; } }
Helper for forcing a connection to localhost . Useful when using regtest mode . Returns the peer object .
33,693
@ GuardedBy ( "lock" ) protected Peer connectTo ( PeerAddress address , boolean incrementMaxConnections , int connectTimeoutMillis ) { checkState ( lock . isHeldByCurrentThread ( ) ) ; VersionMessage ver = getVersionMessage ( ) . duplicate ( ) ; ver . bestHeight = chain == null ? 0 : chain . getBestChainHeight ( ) ; ve...
Creates a version message to send constructs a Peer object and attempts to connect it . Returns the peer on success or null on failure .
33,694
public List < Peer > findPeersOfAtLeastVersion ( long protocolVersion ) { lock . lock ( ) ; try { ArrayList < Peer > results = new ArrayList < > ( peers . size ( ) ) ; for ( Peer peer : peers ) if ( peer . getPeerVersionMessage ( ) . clientVersion >= protocolVersion ) results . add ( peer ) ; return results ; } finally...
Returns an array list of peers that implement the given protocol version or better .
33,695
public List < Peer > findPeersWithServiceMask ( int mask ) { lock . lock ( ) ; try { ArrayList < Peer > results = new ArrayList < > ( peers . size ( ) ) ; for ( Peer peer : peers ) if ( ( peer . getPeerVersionMessage ( ) . localServices & mask ) == mask ) results . add ( peer ) ; return results ; } finally { lock . unl...
Returns an array list of peers that match the requested service bit mask .
33,696
public static Coin valueOf ( final int coins , final int cents ) { checkArgument ( cents < 100 ) ; checkArgument ( cents >= 0 ) ; checkArgument ( coins >= 0 ) ; final Coin coin = COIN . multiply ( coins ) . add ( CENT . multiply ( cents ) ) ; return coin ; }
Convert an amount expressed in the way humans are used to into satoshis .
33,697
public static < T > boolean removeFromList ( T listener , List < ? extends ListenerRegistration < T > > list ) { checkNotNull ( listener ) ; ListenerRegistration < T > item = null ; for ( ListenerRegistration < T > registration : list ) { if ( registration . listener == listener ) { item = registration ; break ; } } re...
Returns true if the listener was removed else false .
33,698
protected void disconnectTransactions ( StoredBlock oldBlock ) throws PrunedException , BlockStoreException { checkState ( lock . isHeldByCurrentThread ( ) ) ; blockStore . beginDatabaseBatchWrite ( ) ; try { StoredUndoableBlock undoBlock = blockStore . getUndoBlock ( oldBlock . getHeader ( ) . getHash ( ) ) ; if ( und...
This is broken for blocks that do not pass BIP30 so all BIP30 - failing blocks which are allowed to fail BIP30 must be checkpointed .
33,699
public List < PaymentProtocol . Output > getOutputs ( ) { List < PaymentProtocol . Output > outputs = new ArrayList < > ( paymentDetails . getOutputsCount ( ) ) ; for ( Protos . Output output : paymentDetails . getOutputsList ( ) ) { Coin amount = output . hasAmount ( ) ? Coin . valueOf ( output . getAmount ( ) ) : nul...
Returns the outputs of the payment request .