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 ; } else { result |= ( tmp & 0x7f ) << 14 ; if ( ( tmp = buffer [ offset ++ ] ) >= 0 ) { result |= tmp << 21 ; } else { result |= ( tmp & 0x7f ) << 21 ; result |= ( tmp = buffer [ offset ++ ] ) << 28 ; if ( tmp < 0 ) { for ( int i = 0 ; i < 5 ; i ++ ) { if ( buffer [ offset ++ ] >= 0 ) { return result ; } } throw ProtobufException . malformedVarint ( ) ; } } } } return result ; }
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 ) & 0xFF ) ; }
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 ) & 0xFF ) ; }
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 ++ ] = ( byte ) ( value >>> 24 ) ; buffer [ offset ++ ] = ( byte ) ( value >>> 16 ) ; buffer [ offset ++ ] = ( byte ) ( value >>> 8 ) ; buffer [ offset ] = ( byte ) ( value >>> 0 ) ; }
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 ++ ] = ( byte ) ( value >>> 32 ) ; buffer [ offset ++ ] = ( byte ) ( value >>> 40 ) ; buffer [ offset ++ ] = ( byte ) ( value >>> 48 ) ; buffer [ offset ] = ( byte ) ( value >>> 56 ) ; }
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 importedObj = proto . findFullyQualifiedObject ( fullyQualifiedName ) ; if ( importedObj != null ) return importedObj ; } return null ; }
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 ( readRawVarint32 ( ) ) ; return true ; case WireFormat . WIRETYPE_START_GROUP : skipMessage ( ) ; checkLastTagWas ( WireFormat . makeTag ( WireFormat . getTagFieldNumber ( tag ) , WireFormat . WIRETYPE_END_GROUP ) ) ; return true ; case WireFormat . WIRETYPE_END_GROUP : return false ; case WireFormat . WIRETYPE_FIXED32 : readRawLittleEndian32 ( ) ; return true ; default : throw ProtobufException . invalidWireType ( ) ; } }
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 ) << 24 ) ; }
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 = readRawByte ( ) ; return ( ( ( long ) b1 & 0xff ) ) | ( ( ( long ) b2 & 0xff ) << 8 ) | ( ( ( long ) b3 & 0xff ) << 16 ) | ( ( ( long ) b4 & 0xff ) << 24 ) | ( ( ( long ) b5 & 0xff ) << 32 ) | ( ( ( long ) b6 & 0xff ) << 40 ) | ( ( ( long ) b7 & 0xff ) << 48 ) | ( ( ( long ) b8 & 0xff ) << 56 ) ; }
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 <= bufferSize - bufferPos ) { final byte [ ] bytes = new byte [ size ] ; System . arraycopy ( buffer , bufferPos , bytes , 0 , size ) ; bufferPos += size ; return bytes ; } else if ( size < buffer . length ) { final byte [ ] bytes = new byte [ size ] ; int pos = bufferSize - bufferPos ; System . arraycopy ( buffer , bufferPos , bytes , 0 , pos ) ; bufferPos = bufferSize ; refillBuffer ( true ) ; while ( size - pos > bufferSize ) { System . arraycopy ( buffer , 0 , bytes , pos , bufferSize ) ; pos += bufferSize ; bufferPos = bufferSize ; refillBuffer ( true ) ; } System . arraycopy ( buffer , 0 , bytes , pos , size - pos ) ; bufferPos = size - pos ; return bytes ; } else { final int originalBufferPos = bufferPos ; final int originalBufferSize = bufferSize ; totalBytesRetired += bufferSize ; bufferPos = 0 ; bufferSize = 0 ; int sizeLeft = size - ( originalBufferSize - originalBufferPos ) ; final List < byte [ ] > chunks = new ArrayList < byte [ ] > ( ) ; while ( sizeLeft > 0 ) { final byte [ ] chunk = new byte [ Math . min ( sizeLeft , buffer . length ) ] ; int pos = 0 ; while ( pos < chunk . length ) { final int n = ( input == null ) ? - 1 : input . read ( chunk , pos , chunk . length - pos ) ; if ( n == - 1 ) { throw ProtobufException . truncatedMessage ( ) ; } totalBytesRetired += n ; pos += n ; } sizeLeft -= chunk . length ; chunks . add ( chunk ) ; } final byte [ ] bytes = new byte [ size ] ; int pos = originalBufferSize - originalBufferPos ; System . arraycopy ( buffer , originalBufferPos , bytes , 0 , pos ) ; for ( final byte [ ] chunk : chunks ) { System . arraycopy ( chunk , 0 , bytes , pos , chunk . length ) ; pos += chunk . length ; } return bytes ; } }
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 NumberFormatException ( STRING . deser ( buffer , start , length ) ) ; return parseInt ( buffer , start + 1 , length - 1 , radix , false ) ; } return parseInt ( buffer , start , length , radix , true ) ; }
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 = dividend - quotient * divisor ; return rem - ( compareUnsigned ( rem , divisor ) >= 0 ? divisor : 0 ) ; }
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 ( ) ; } mGLThread = new GLThread ( mThisWeakRef ) ; if ( renderMode != RENDERMODE_CONTINUOUSLY ) { mGLThread . setRenderMode ( renderMode ) ; } mGLThread . start ( ) ; } mDetached = false ; }
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 ) ; } return client . build ( ) ; }
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 = trustManagerFactory . getTrustManagers ( ) ; if ( trustManagers . length != 1 || ! ( trustManagers [ 0 ] instanceof X509TrustManager ) ) { throw new IllegalStateException ( "Unexpected default trust managers:" + Arrays . toString ( trustManagers ) ) ; } X509TrustManager trustManager = ( X509TrustManager ) trustManagers [ 0 ] ; client . sslSocketFactory ( new TLSSocketFactory ( ) , trustManager ) ; ConnectionSpec cs = new ConnectionSpec . Builder ( ConnectionSpec . MODERN_TLS ) . tlsVersions ( TlsVersion . TLS_1_2 , TlsVersion . TLS_1_1 ) . build ( ) ; List < ConnectionSpec > specs = new ArrayList < > ( ) ; specs . add ( cs ) ; specs . add ( ConnectionSpec . COMPATIBLE_TLS ) ; specs . add ( ConnectionSpec . CLEARTEXT ) ; client . connectionSpecs ( specs ) ; } catch ( Exception exc ) { Log . e ( TAG , "Error while setting TLS" , exc ) ; } return client ; }
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 ) ; mEglConfig = mEGLConfigChooser . chooseConfig ( mEgl , mEglDisplay ) ; } else { } if ( mEglContext == null ) { mEglContext = mEGLContextFactory . createContext ( mEgl , mEglDisplay , mEglConfig ) ; if ( mEglContext == null || mEglContext == EGL10 . EGL_NO_CONTEXT ) { throw new RuntimeException ( "createContext failed" ) ; } } else { } mEglSurface = null ; }
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 = null ; if ( arr . length > 1 ) { title = arr [ 1 ] ; } return new UserCommand ( id , title ) ; }
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 , ProviderContract . Artwork . TOKEN ) ; allColumnProjectionMap . put ( ProviderContract . Artwork . TITLE , ProviderContract . Artwork . TITLE ) ; allColumnProjectionMap . put ( ProviderContract . Artwork . BYLINE , ProviderContract . Artwork . BYLINE ) ; allColumnProjectionMap . put ( ProviderContract . Artwork . ATTRIBUTION , ProviderContract . Artwork . ATTRIBUTION ) ; allColumnProjectionMap . put ( ProviderContract . Artwork . PERSISTENT_URI , ProviderContract . Artwork . PERSISTENT_URI ) ; allColumnProjectionMap . put ( ProviderContract . Artwork . WEB_URI , ProviderContract . Artwork . WEB_URI ) ; allColumnProjectionMap . put ( ProviderContract . Artwork . METADATA , ProviderContract . Artwork . METADATA ) ; allColumnProjectionMap . put ( ProviderContract . Artwork . DATA , ProviderContract . Artwork . DATA ) ; allColumnProjectionMap . put ( ProviderContract . Artwork . DATE_ADDED , ProviderContract . Artwork . DATE_ADDED ) ; allColumnProjectionMap . put ( ProviderContract . Artwork . DATE_MODIFIED , ProviderContract . Artwork . DATE_MODIFIED ) ; return allColumnProjectionMap ; }
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" ) ; return notification . getSign ( ) . equals ( SignatureUtil . sign ( notificationMap , paySetting . getKey ( ) ) ) ; }
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 ) socketAddress ; if ( poolManager . getDiscoveryClient ( ) != null ) { final DiscoveryClient mgr = poolManager . getDiscoveryClient ( ) ; final Application app = mgr . getApplication ( appId ) ; if ( app != null ) { final List < InstanceInfo > instances = app . getInstances ( ) ; for ( InstanceInfo info : instances ) { final String hostName = info . getHostName ( ) ; if ( hostName . equalsIgnoreCase ( isa . getHostName ( ) ) ) { final String ip = info . getIPAddr ( ) ; String port = info . getMetadata ( ) . get ( "evcache.port" ) ; if ( port == null ) port = "11211" ; result = hostName + '/' + ip + ':' + port ; break ; } } } else { result = ( ( InetSocketAddress ) socketAddress ) . getHostName ( ) + '/' + ( ( InetSocketAddress ) socketAddress ) . getAddress ( ) . getHostAddress ( ) + ":11211" ; } } else { result = ( ( InetSocketAddress ) socketAddress ) . getHostName ( ) + '/' + ( ( InetSocketAddress ) socketAddress ) . getAddress ( ) . getHostAddress ( ) + ":11211" ; } } else { result = String . valueOf ( socketAddress ) ; if ( result . startsWith ( "/" ) ) { result = result . substring ( 1 ) ; } } socketAddresses . put ( node , result ) ; } return result ; }
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 ( EVCacheConfig . getInstance ( ) . getChainedBooleanProperty ( APP + ".use.simple.node.list.provider" , "evcache.use.simple.node.list.provider" , Boolean . FALSE , null ) . get ( ) ) { provider = new SimpleNodeListProvider ( ) ; } else { provider = new DiscoveryNodeListProvider ( applicationInfoManager , discoveryClient , APP ) ; } final EVCacheClientPool pool = new EVCacheClientPool ( APP , provider , asyncExecutor , this ) ; scheduleRefresh ( pool ) ; poolMap . put ( APP , pool ) ; }
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 ( memcachedReadInstancesByServerGroup . containsKey ( serverGroup ) ) { EVCacheMetricsFactory . increment ( _appName , null , serverGroup . getName ( ) , _appName + "-" + serverGroup . getName ( ) + "-WRITE_ONLY" ) ; memcachedReadInstancesByServerGroup . remove ( serverGroup ) ; } } else { if ( ! memcachedReadInstancesByServerGroup . containsKey ( serverGroup ) ) { EVCacheMetricsFactory . increment ( _appName , null , serverGroup . getName ( ) , _appName + "-" + serverGroup . getName ( ) + "-READ_ENABLED" ) ; memcachedReadInstancesByServerGroup . put ( serverGroup , memcachedInstancesByServerGroup . get ( serverGroup ) ) ; } } final List < EVCacheClient > clients = memcachedReadInstancesByServerGroup . get ( serverGroup ) ; if ( clients != null && ! clients . isEmpty ( ) ) { final EVCacheClient client = clients . get ( 0 ) ; if ( client != null ) { final EVCacheConnectionObserver connectionObserver = client . getConnectionObserver ( ) ; if ( connectionObserver != null ) { final int activeServerCount = connectionObserver . getActiveServerCount ( ) ; final int inActiveServerCount = connectionObserver . getInActiveServerCount ( ) ; if ( inActiveServerCount > activeServerCount ) { memcachedReadInstancesByServerGroup . remove ( serverGroup ) ; } } } } } if ( memcachedReadInstancesByServerGroup . size ( ) != memcachedFallbackReadInstances . getSize ( ) ) { memcachedFallbackReadInstances = new ServerGroupCircularIterator ( memcachedReadInstancesByServerGroup . keySet ( ) ) ; Map < String , Set < ServerGroup > > readServerGroupByZoneMap = new ConcurrentHashMap < String , Set < ServerGroup > > ( ) ; for ( ServerGroup serverGroup : memcachedReadInstancesByServerGroup . keySet ( ) ) { Set < ServerGroup > serverGroupList = readServerGroupByZoneMap . get ( serverGroup . getZone ( ) ) ; if ( serverGroupList == null ) { serverGroupList = new HashSet < ServerGroup > ( ) ; readServerGroupByZoneMap . put ( serverGroup . getZone ( ) , serverGroupList ) ; } serverGroupList . add ( serverGroup ) ; } Map < String , ServerGroupCircularIterator > _readServerGroupByZone = new ConcurrentHashMap < String , ServerGroupCircularIterator > ( ) ; for ( Entry < String , Set < ServerGroup > > readServerGroupByZoneEntry : readServerGroupByZoneMap . entrySet ( ) ) { _readServerGroupByZone . put ( readServerGroupByZoneEntry . getKey ( ) , new ServerGroupCircularIterator ( readServerGroupByZoneEntry . getValue ( ) ) ) ; } this . readServerGroupByZone = _readServerGroupByZone ; localServerGroupIterator = readServerGroupByZone . get ( _zone ) ; } }
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 . debug ( "List of Nodes = " + nodeListString ) ; if ( nodeListString != null && nodeListString . length ( ) > 0 ) return bootstrapFromSystemProperty ( nodeListString ) ; if ( env != null && region != null ) return bootstrapFromEureka ( appName ) ; return Collections . < ServerGroup , EVCacheServerGroupConfig > emptyMap ( ) ; }
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 for key " + key + " is " + didSucceed ) ; } } if ( ! verboseMode ) { System . out . println ( "finished setting key " + key ) ; } } catch ( EVCacheException e ) { e . printStackTrace ( ) ; } }
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.netflix.evcache.sample.EVCacheClientSample" ) ; } try { EVCacheClientSample evCacheClientSample = new EVCacheClientSample ( ) ; for ( int i = 0 ; i < 10 ; i ++ ) { String key = "key_" + i ; String value = "data_" + i ; int ttl = 86400 ; evCacheClientSample . setKey ( key , value , ttl ) ; } for ( int i = 0 ; i < 10 ; i ++ ) { String key = "key_" + i ; String value = evCacheClientSample . getKey ( key ) ; System . out . println ( "Get of " + key + " returned " + value ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; } System . exit ( 0 ) ; }
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 ( ) ) { Map < String , CachedData > rv = new HashMap < String , CachedData > ( ) ; rv . put ( key , ( CachedData ) cd . getData ( ) ) ; if ( log . isDebugEnabled ( ) ) log . debug ( "Data : " + rv ) ; return rv ; } else { final List < String > keys = cd . getChunkKeys ( ) ; if ( log . isDebugEnabled ( ) ) log . debug ( "Keys - " + keys ) ; final Map < String , CachedData > dataMap = evcacheMemcachedClient . asyncGetBulk ( keys , chunkingTranscoder , null , "GetAllChunksOperation" ) . getSome ( readTimeout . get ( ) . intValue ( ) , TimeUnit . MILLISECONDS , false , false ) ; if ( log . isDebugEnabled ( ) ) log . debug ( "Datamap " + dataMap ) ; return dataMap ; } } catch ( Exception e ) { log . error ( e . getMessage ( ) , e ) ; } return null ; }
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 ) == NODE_BLOOM ) return true ; return false ; }
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 . compareTo ( BigInteger . valueOf ( Long . MIN_VALUE ) ) < 0 ) throw new ArithmeticException ( "Overflow" ) ; return Fiat . valueOf ( fiat . currencyCode , converted . longValue ( ) ) ; }
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 ( coin . value ) ) . divide ( BigInteger . valueOf ( fiat . value ) ) ; if ( converted . compareTo ( BigInteger . valueOf ( Long . MAX_VALUE ) ) > 0 || converted . compareTo ( BigInteger . valueOf ( Long . MIN_VALUE ) ) < 0 ) throw new ArithmeticException ( "Overflow" ) ; try { return Coin . valueOf ( converted . longValue ( ) ) ; } catch ( IllegalArgumentException x ) { throw new ArithmeticException ( "Overflow: " + x . getMessage ( ) ) ; } }
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 . length ) ; if ( version != 0x01 ) throw new AddressFormatException . InvalidPrefix ( "Mismatched version number: " + version ) ; if ( bytes . length != 38 ) throw new AddressFormatException . InvalidDataLength ( "Wrong number of bytes: " + bytes . length ) ; boolean hasLotAndSequence = ( bytes [ 1 ] & 0x04 ) != 0 ; boolean compressed = ( bytes [ 1 ] & 0x20 ) != 0 ; if ( ( bytes [ 1 ] & 0x01 ) != 0 ) throw new AddressFormatException ( "Bit 0x01 reserved for future use." ) ; if ( ( bytes [ 1 ] & 0x02 ) != 0 ) throw new AddressFormatException ( "Bit 0x02 reserved for future use." ) ; if ( ( bytes [ 1 ] & 0x08 ) != 0 ) throw new AddressFormatException ( "Bit 0x08 reserved for future use." ) ; if ( ( bytes [ 1 ] & 0x10 ) != 0 ) throw new AddressFormatException ( "Bit 0x10 reserved for future use." ) ; final int byte0 = bytes [ 0 ] & 0xff ; final boolean ecMultiply ; if ( byte0 == 0x42 ) { if ( ( bytes [ 1 ] & 0xc0 ) != 0xc0 ) throw new AddressFormatException ( "Bits 0x40 and 0x80 must be set for non-EC-multiplied keys." ) ; ecMultiply = false ; if ( hasLotAndSequence ) throw new AddressFormatException ( "Non-EC-multiplied keys cannot have lot/sequence." ) ; } else if ( byte0 == 0x43 ) { if ( ( bytes [ 1 ] & 0xc0 ) != 0x00 ) throw new AddressFormatException ( "Bits 0x40 and 0x80 must be cleared for EC-multiplied keys." ) ; ecMultiply = true ; } else { throw new AddressFormatException ( "Second byte must by 0x42 or 0x43." ) ; } byte [ ] addressHash = Arrays . copyOfRange ( bytes , 2 , 6 ) ; byte [ ] content = Arrays . copyOfRange ( bytes , 6 , 38 ) ; return new BIP38PrivateKey ( params , bytes , ecMultiply , compressed , hasLotAndSequence , addressHash , content ) ; }
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 . getKey ( purpose ) ; checkState ( followedKey . getChildNumber ( ) . equals ( followingKey . getChildNumber ( ) ) , "Following keychains should be in sync" ) ; keys . add ( followingKey ) ; } List < ECKey > marriedKeys = keys . build ( ) ; Script redeemScript = ScriptBuilder . createRedeemScript ( sigsRequiredToSpend , marriedKeys ) ; return ScriptBuilder . createP2SHOutputScript ( redeemScript ) ; }
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 . getDescription ( ) ) ; } for ( WalletTransaction wtx : wallet . getWalletTransactions ( ) ) { Protos . Transaction txProto = makeTxProto ( wtx ) ; walletBuilder . addTransaction ( txProto ) ; } walletBuilder . addAllKey ( wallet . serializeKeyChainGroupToProtobuf ( ) ) ; for ( Script script : wallet . getWatchedScripts ( ) ) { Protos . Script protoScript = Protos . Script . newBuilder ( ) . setProgram ( ByteString . copyFrom ( script . getProgram ( ) ) ) . setCreationTimestamp ( script . getCreationTimeSeconds ( ) * 1000 ) . build ( ) ; walletBuilder . addWatchedScript ( protoScript ) ; } Sha256Hash lastSeenBlockHash = wallet . getLastBlockSeenHash ( ) ; if ( lastSeenBlockHash != null ) { walletBuilder . setLastSeenBlockHash ( hashToByteString ( lastSeenBlockHash ) ) ; walletBuilder . setLastSeenBlockHeight ( wallet . getLastBlockSeenHeight ( ) ) ; } if ( wallet . getLastBlockSeenTimeSecs ( ) > 0 ) walletBuilder . setLastSeenBlockTimeSecs ( wallet . getLastBlockSeenTimeSecs ( ) ) ; KeyCrypter keyCrypter = wallet . getKeyCrypter ( ) ; if ( keyCrypter == null ) { walletBuilder . setEncryptionType ( EncryptionType . UNENCRYPTED ) ; } else { walletBuilder . setEncryptionType ( keyCrypter . getUnderstoodEncryptionType ( ) ) ; if ( keyCrypter instanceof KeyCrypterScrypt ) { KeyCrypterScrypt keyCrypterScrypt = ( KeyCrypterScrypt ) keyCrypter ; walletBuilder . setEncryptionParameters ( keyCrypterScrypt . getScryptParameters ( ) ) ; } else { throw new RuntimeException ( "The wallet has encryption of type '" + keyCrypter . getUnderstoodEncryptionType ( ) + "' but this WalletProtobufSerializer does not know how to persist this." ) ; } } if ( wallet . getKeyRotationTime ( ) != null ) { long timeSecs = wallet . getKeyRotationTime ( ) . getTime ( ) / 1000 ; walletBuilder . setKeyRotationTime ( timeSecs ) ; } populateExtensions ( wallet , walletBuilder ) ; for ( Map . Entry < String , ByteString > entry : wallet . getTags ( ) . entrySet ( ) ) { Protos . Tag . Builder tag = Protos . Tag . newBuilder ( ) . setTag ( entry . getKey ( ) ) . setData ( entry . getValue ( ) ) ; walletBuilder . addTags ( tag ) ; } walletBuilder . setVersion ( wallet . getVersion ( ) ) ; return walletBuilder . build ( ) ; }
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 NetworkParameters . fromID ( network ) != null ; } catch ( IOException x ) { return false ; } }
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 database block store - no chain head pointer" ) ; } Sha256Hash hash = Sha256Hash . wrap ( rs . getBytes ( 1 ) ) ; rs . close ( ) ; this . chainHeadBlock = get ( hash ) ; this . chainHeadHash = hash ; if ( this . chainHeadBlock == null ) { throw new BlockStoreException ( "corrupt database block store - head block not found" ) ; } ps . setString ( 1 , VERIFIED_CHAIN_HEAD_SETTING ) ; rs = ps . executeQuery ( ) ; if ( ! rs . next ( ) ) { throw new BlockStoreException ( "corrupt database block store - no verified chain head pointer" ) ; } hash = Sha256Hash . wrap ( rs . getBytes ( 1 ) ) ; rs . close ( ) ; ps . close ( ) ; this . verifiedChainHeadBlock = get ( hash ) ; this . verifiedChainHeadHash = hash ; if ( this . verifiedChainHeadBlock == null ) { throw new BlockStoreException ( "corrupt database block store - verified head block not found" ) ; } }
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 = BigInteger . ZERO ; if ( rs . next ( ) ) { return BigInteger . valueOf ( rs . getLong ( 1 ) ) ; } return balance ; } catch ( SQLException ex ) { throw new BlockStoreException ( ex ) ; } finally { if ( s != null ) { try { s . close ( ) ; } catch ( SQLException e ) { throw new BlockStoreException ( "Could not close statement" ) ; } } } }
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 ( absolutePath ) ) { if ( ! create ) throw new IllegalArgumentException ( String . format ( Locale . US , "No key found for %s path %s." , relativePath ? "relative" : "absolute" , HDUtils . formatPath ( path ) ) ) ; checkArgument ( absolutePath . size ( ) > 0 , "Can't derive the master key: nothing to derive from." ) ; DeterministicKey parent = get ( absolutePath . subList ( 0 , absolutePath . size ( ) - 1 ) , false , true ) ; putKey ( HDKeyDerivation . deriveChildKey ( parent , absolutePath . get ( absolutePath . size ( ) - 1 ) ) ) ; } return keys . get ( absolutePath ) ; }
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 , addressBytes , 1 , payload . length ) ; byte [ ] checksum = Sha256Hash . hashTwice ( addressBytes , 0 , payload . length + 1 ) ; System . arraycopy ( checksum , 0 , addressBytes , payload . length + 1 , 4 ) ; return Base58 . encode ( addressBytes ) ; }
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 ; if ( digit < 0 ) { throw new AddressFormatException . InvalidCharacter ( c , i ) ; } input58 [ i ] = ( byte ) digit ; } int zeros = 0 ; while ( zeros < input58 . length && input58 [ zeros ] == 0 ) { ++ zeros ; } byte [ ] decoded = new byte [ input . length ( ) ] ; int outputStart = decoded . length ; for ( int inputStart = zeros ; inputStart < input58 . length ; ) { decoded [ -- outputStart ] = divmod ( input58 , inputStart , 58 , 256 ) ; if ( input58 [ inputStart ] == 0 ) { ++ inputStart ; } } while ( outputStart < decoded . length && decoded [ outputStart ] == 0 ) { ++ outputStart ; } return Arrays . copyOfRange ( decoded , outputStart - zeros , decoded . length ) ; }
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 - 4 ) ; byte [ ] checksum = Arrays . copyOfRange ( decoded , decoded . length - 4 , decoded . length ) ; byte [ ] actualChecksum = Arrays . copyOfRange ( Sha256Hash . hashTwice ( data ) , 0 , 4 ) ; if ( ! Arrays . equals ( checksum , actualChecksum ) ) throw new AddressFormatException . InvalidChecksum ( ) ; return data ; }
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 ; } return ( byte ) remainder ; }
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 , chainFileName ) ; if ( reset ) { try { CheckpointManager . checkpoint ( params , CheckpointManager . openStream ( params ) , store , wallet . getEarliestKeyCreationTime ( ) ) ; StoredBlock head = store . getChainHead ( ) ; System . out . println ( "Skipped to checkpoint " + head . getHeight ( ) + " at " + Utils . dateTimeFormat ( head . getHeader ( ) . getTimeSeconds ( ) * 1000 ) ) ; } catch ( IOException x ) { System . out . println ( "Could not load checkpoints: " + x . getMessage ( ) ) ; } } chain = new BlockChain ( params , wallet , store ) ; } else if ( mode == ValidationMode . FULL ) { store = new H2FullPrunedBlockStore ( params , chainFileName . getAbsolutePath ( ) , 5000 ) ; chain = new FullPrunedBlockChain ( params , wallet , ( FullPrunedBlockStore ) store ) ; } wallet . autosaveToFile ( walletFile , 5 , TimeUnit . SECONDS , null ) ; if ( peerGroup == null ) { peerGroup = new PeerGroup ( params , chain ) ; } peerGroup . setUserAgent ( "WalletTool" , "1.0" ) ; if ( params == RegTestParams . get ( ) ) peerGroup . setMinBroadcastConnections ( 1 ) ; peerGroup . addWallet ( wallet ) ; if ( options . has ( "peers" ) ) { String peersFlag = ( String ) options . valueOf ( "peers" ) ; String [ ] peerAddrs = peersFlag . split ( "," ) ; for ( String peer : peerAddrs ) { try { peerGroup . addAddress ( new PeerAddress ( params , InetAddress . getByName ( peer ) ) ) ; } catch ( UnknownHostException e ) { System . err . println ( "Could not understand peer domain name/IP address: " + peer + ": " + e . getMessage ( ) ) ; System . exit ( 1 ) ; } } } else { peerGroup . setRequiredServices ( 0 ) ; } }
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 ) c ^= 0x3d4233dd ; if ( ( c0 & 16 ) != 0 ) c ^= 0x2a1462b3 ; } return c ; }
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 ) ; } ret [ hrpLength ] = 0 ; return ret ; }
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 , combined , hrpExpanded . length , values . length ) ; return polymod ( combined ) == 1 ; }
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 , hrpExpanded . length , values . length ) ; int mod = polymod ( enc ) ^ 1 ; byte [ ] ret = new byte [ 6 ] ; for ( int i = 0 ; i < 6 ; ++ i ) { ret [ i ] = ( byte ) ( ( mod >>> ( 5 * ( 5 - i ) ) ) & 31 ) ; } return ret ; }
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 ) ; byte [ ] combined = new byte [ values . length + checksum . length ] ; System . arraycopy ( values , 0 , combined , 0 , values . length ) ; System . arraycopy ( checksum , 0 , combined , values . length , checksum . length ) ; StringBuilder sb = new StringBuilder ( hrp . length ( ) + 1 + combined . length ) ; sb . append ( hrp ) ; sb . append ( '1' ) ; for ( byte b : combined ) { sb . append ( CHARSET . charAt ( b ) ) ; } return sb . toString ( ) ; }
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 . InvalidDataLength ( "Input too long: " + str . length ( ) ) ; for ( int i = 0 ; i < str . length ( ) ; ++ i ) { char c = str . charAt ( i ) ; if ( c < 33 || c > 126 ) throw new AddressFormatException . InvalidCharacter ( c , i ) ; if ( c >= 'a' && c <= 'z' ) { if ( upper ) throw new AddressFormatException . InvalidCharacter ( c , i ) ; lower = true ; } if ( c >= 'A' && c <= 'Z' ) { if ( lower ) throw new AddressFormatException . InvalidCharacter ( c , i ) ; upper = true ; } } final int pos = str . lastIndexOf ( '1' ) ; if ( pos < 1 ) throw new AddressFormatException . InvalidPrefix ( "Missing human-readable part" ) ; final int dataPartLength = str . length ( ) - 1 - pos ; if ( dataPartLength < 6 ) throw new AddressFormatException . InvalidDataLength ( "Data part too short: " + dataPartLength ) ; byte [ ] values = new byte [ dataPartLength ] ; for ( int i = 0 ; i < dataPartLength ; ++ i ) { char c = str . charAt ( i + pos + 1 ) ; if ( CHARSET_REV [ c ] == - 1 ) throw new AddressFormatException . InvalidCharacter ( c , i + pos + 1 ) ; values [ i ] = CHARSET_REV [ c ] ; } String hrp = str . substring ( 0 , pos ) . toLowerCase ( Locale . ROOT ) ; if ( ! verifyChecksum ( hrp , values ) ) throw new AddressFormatException . InvalidChecksum ( ) ; return new Bech32Data ( hrp , Arrays . copyOfRange ( values , 0 , values . length - 6 ) ) ; }
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" ) ; TransactionOutput out = transaction . getOutput ( ( int ) outpoint . getIndex ( ) ) ; if ( ! out . isAvailableForSpending ( ) ) { if ( getParentTransaction ( ) . equals ( outpoint . fromTx ) ) { return ConnectionResult . SUCCESS ; } else if ( mode == ConnectMode . DISCONNECT_ON_CONFLICT ) { out . markAsUnspent ( ) ; } else if ( mode == ConnectMode . ABORT_ON_CONFLICT ) { outpoint . fromTx = out . getParentTransaction ( ) ; return TransactionInput . ConnectionResult . ALREADY_SPENT ; } } connect ( out ) ; return TransactionInput . ConnectionResult . SUCCESS ; }
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 ; outpoint . connectedOutput = null ; } else { return false ; } if ( connectedOutput != null && connectedOutput . getSpentBy ( ) == this ) { connectedOutput . markAsUnspent ( ) ; return true ; } else { return false ; } }
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 ( getOutpoint ( ) . getIndex ( ) != output . getIndex ( ) ) throw new VerificationException ( "This input refers to a different output on the given tx." ) ; } Script pubKey = output . getScriptPubKey ( ) ; getScriptSig ( ) . correctlySpends ( getParentTransaction ( ) , getIndex ( ) , getWitness ( ) , getValue ( ) , pubKey , Script . ALL_VERIFY_FLAGS ) ; }
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 . isP2PKH ( connectedScript ) ) { byte [ ] addressBytes = ScriptPattern . extractHashFromP2PKH ( connectedScript ) ; return RedeemData . of ( keyBag . findKeyFromPubKeyHash ( addressBytes , Script . ScriptType . P2PKH ) , connectedScript ) ; } else if ( ScriptPattern . isP2WPKH ( connectedScript ) ) { byte [ ] addressBytes = ScriptPattern . extractHashFromP2WH ( connectedScript ) ; return RedeemData . of ( keyBag . findKeyFromPubKeyHash ( addressBytes , Script . ScriptType . P2WPKH ) , connectedScript ) ; } else if ( ScriptPattern . isP2PK ( connectedScript ) ) { byte [ ] pubkeyBytes = ScriptPattern . extractKeyFromP2PK ( connectedScript ) ; return RedeemData . of ( keyBag . findKeyFromPubKey ( pubkeyBytes ) , connectedScript ) ; } else if ( ScriptPattern . isP2SH ( connectedScript ) ) { byte [ ] scriptHash = ScriptPattern . extractHashFromP2SH ( connectedScript ) ; return keyBag . findRedeemDataFromScriptHash ( scriptHash ) ; } else { throw new ScriptException ( ScriptError . SCRIPT_ERR_UNKNOWN_ERROR , "Could not understand form of connected output script: " + connectedScript ) ; } }
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 ( ) ; if ( adjustment < 0 ) channels . closeConnections ( - adjustment ) ; }
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 = ! willSendFilter ; } finally { lock . unlock ( ) ; } }
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 = Lists . newLinkedList ( ) ; for ( PeerDiscovery peerDiscovery : peerDiscoverers ) { InetSocketAddress [ ] addresses ; try { addresses = peerDiscovery . getPeers ( requiredServices , peerDiscoveryTimeoutMillis , TimeUnit . MILLISECONDS ) ; } catch ( PeerDiscoveryException e ) { log . warn ( e . getMessage ( ) ) ; continue ; } for ( InetSocketAddress address : addresses ) addressList . add ( new PeerAddress ( params , address ) ) ; if ( addressList . size ( ) >= maxPeersToDiscoverCount ) break ; } if ( ! addressList . isEmpty ( ) ) { for ( PeerAddress address : addressList ) { addInactive ( address ) ; } final ImmutableSet < PeerAddress > peersDiscoveredSet = ImmutableSet . copyOf ( addressList ) ; for ( final ListenerRegistration < PeerDiscoveredEventListener > registration : peerDiscoveredEventListeners ) { registration . executor . execute ( new Runnable ( ) { public void run ( ) { registration . listener . onPeersDiscovered ( peersDiscoveredSet ) ; } } ) ; } } watch . stop ( ) ; log . info ( "Peer discovery took {} and returned {} items" , watch , addressList . size ( ) ) ; return addressList . size ( ) ; }
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 executor . submit ( new Runnable ( ) { public void run ( ) { try { log . info ( "Starting ..." ) ; channels . startAsync ( ) ; channels . awaitRunning ( ) ; triggerConnections ( ) ; setupPinging ( ) ; } catch ( Throwable e ) { log . error ( "Exception when starting up" , e ) ; } } } ) ; }
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 ( e ) ; } }
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 . removeScriptsChangeEventListener ( walletScriptsEventListener ) ; wallet . setTransactionBroadcaster ( null ) ; for ( Peer peer : peers ) { peer . removeWallet ( wallet ) ; } }
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 ( ) ; ver . time = Utils . currentTimeSeconds ( ) ; ver . receivingAddr = address ; ver . receivingAddr . setParent ( ver ) ; Peer peer = createPeer ( address , ver ) ; peer . addConnectedEventListener ( Threading . SAME_THREAD , startupListener ) ; peer . addDisconnectedEventListener ( Threading . SAME_THREAD , startupListener ) ; peer . setMinProtocolVersion ( vMinRequiredProtocolVersion ) ; pendingPeers . add ( peer ) ; try { log . info ( "Attempting connection to {} ({} connected, {} pending, {} max)" , address , peers . size ( ) , pendingPeers . size ( ) , maxConnections ) ; ListenableFuture < SocketAddress > future = channels . openConnection ( address . toSocketAddress ( ) , peer ) ; if ( future . isDone ( ) ) Uninterruptibles . getUninterruptibly ( future ) ; } catch ( ExecutionException e ) { Throwable cause = Throwables . getRootCause ( e ) ; log . warn ( "Failed to connect to " + address + ": " + cause . getMessage ( ) ) ; handlePeerDeath ( peer , cause ) ; return null ; } peer . setSocketTimeout ( connectTimeoutMillis ) ; if ( incrementMaxConnections ) { maxConnections ++ ; } return peer ; }
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 { lock . unlock ( ) ; } }
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 . unlock ( ) ; } }
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 ; } } return item != null && list . remove ( item ) ; }
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 ( undoBlock == null ) throw new PrunedException ( oldBlock . getHeader ( ) . getHash ( ) ) ; TransactionOutputChanges txOutChanges = undoBlock . getTxOutChanges ( ) ; for ( UTXO out : txOutChanges . txOutsSpent ) blockStore . addUnspentTransactionOutput ( out ) ; for ( UTXO out : txOutChanges . txOutsCreated ) blockStore . removeUnspentTransactionOutput ( out ) ; } catch ( PrunedException e ) { blockStore . abortDatabaseBatchWrite ( ) ; throw e ; } catch ( BlockStoreException e ) { blockStore . abortDatabaseBatchWrite ( ) ; throw e ; } }
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 ( ) ) : null ; outputs . add ( new PaymentProtocol . Output ( amount , output . getScript ( ) . toByteArray ( ) ) ) ; } return outputs ; }
Returns the outputs of the payment request .