idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
33,800 | public synchronized void checkState ( State ... requiredStates ) throws IllegalStateException { for ( State requiredState : requiredStates ) { if ( requiredState . equals ( currentState ) ) { return ; } } throw new IllegalStateException ( String . format ( Locale . US , "Expected states %s, but in state %s" , Lists . n... | Checks that the machine is in one of the given states . Throws if it isn t . |
33,801 | public synchronized void transition ( State newState ) throws IllegalStateException { if ( transitions . containsEntry ( currentState , newState ) ) { currentState = newState ; } else { throw new IllegalStateException ( String . format ( Locale . US , "Attempted invalid transition from %s to %s" , currentState , newSta... | Transitions to a new state provided that the required transition exists |
33,802 | public double getFalsePositiveRate ( int elements ) { return pow ( 1 - pow ( E , - 1.0 * ( hashFuncs * elements ) / ( data . length * 8 ) ) , hashFuncs ) ; } | Returns the theoretical false positive rate of this filter if were to contain the given number of elements . |
33,803 | public synchronized boolean contains ( byte [ ] object ) { for ( int i = 0 ; i < hashFuncs ; i ++ ) { if ( ! Utils . checkBitLE ( data , murmurHash3 ( data , nTweak , i , object ) ) ) return false ; } return true ; } | Returns true if the given object matches the filter either because it was inserted or because we have a false - positive . |
33,804 | public synchronized void insert ( byte [ ] object ) { for ( int i = 0 ; i < hashFuncs ; i ++ ) Utils . setBitLE ( data , murmurHash3 ( data , nTweak , i , object ) ) ; } | Insert the given arbitrary data into the filter |
33,805 | public synchronized void merge ( BloomFilter filter ) { if ( ! this . matchesAll ( ) && ! filter . matchesAll ( ) ) { checkArgument ( filter . data . length == this . data . length && filter . hashFuncs == this . hashFuncs && filter . nTweak == this . nTweak ) ; for ( int i = 0 ; i < data . length ; i ++ ) this . data ... | Copies filter into this . Filter must have the same size hash function count and nTweak or an IllegalArgumentException will be thrown . |
33,806 | public synchronized BloomUpdate getUpdateFlag ( ) { if ( nFlags == 0 ) return BloomUpdate . UPDATE_NONE ; else if ( nFlags == 1 ) return BloomUpdate . UPDATE_ALL ; else if ( nFlags == 2 ) return BloomUpdate . UPDATE_P2PUBKEY_ONLY ; else throw new IllegalStateException ( "Unknown flag combination" ) ; } | The update flag controls how application of the filter to a block modifies the filter . See the enum javadocs for information on what occurs and when . |
33,807 | public synchronized FilteredBlock applyAndUpdate ( Block block ) { List < Transaction > txns = block . getTransactions ( ) ; List < Sha256Hash > txHashes = new ArrayList < > ( txns . size ( ) ) ; List < Transaction > matched = Lists . newArrayList ( ) ; byte [ ] bits = new byte [ ( int ) Math . ceil ( txns . size ( ) /... | Creates a new FilteredBlock from the given Block using this filter to select transactions . Matches can cause the filter to be updated with the matched element this ensures that when a filter is applied to a block spends of matched transactions are also matched . However it means this filter can be mutated by the opera... |
33,808 | public < T > OverlayUI < T > overlayUI ( String name ) { try { checkGuiThread ( ) ; URL location = GuiUtils . getResource ( name ) ; FXMLLoader loader = new FXMLLoader ( location ) ; Pane ui = loader . load ( ) ; T controller = loader . getController ( ) ; OverlayUI < T > pair = new OverlayUI < T > ( ui , controller ) ... | Loads the FXML file with the given name blurs out the main UI and puts this one on top . |
33,809 | public static void handleCrashesOnThisThread ( ) { Thread . currentThread ( ) . setUncaughtExceptionHandler ( ( thread , exception ) -> { GuiUtils . crashAlert ( Throwables . getRootCause ( exception ) ) ; } ) ; } | Show a GUI alert box for any unhandled exceptions that propagate out of this thread . |
33,810 | public static URL getResource ( String name ) { if ( false ) return unchecked ( ( ) -> new URL ( "file:///your/path/here/src/main/wallettemplate/" + name ) ) ; else return MainController . class . getResource ( name ) ; } | A useful helper for development purposes . Used as a switch for loading files from local disk allowing live editing whilst the app runs without rebuilds . |
33,811 | void dumpStats ( ) { long wallTimeNanos = totalStopwatch . elapsed ( TimeUnit . NANOSECONDS ) ; long dbtime = 0 ; for ( String name : methodCalls . keySet ( ) ) { long calls = methodCalls . get ( name ) ; long time = methodTotalTime . get ( name ) ; dbtime += time ; long average = time / calls ; double proportion = ( t... | and cache hit rates etc .. |
33,812 | public MonetaryFormat negativeSign ( char negativeSign ) { checkArgument ( ! Character . isDigit ( negativeSign ) ) ; checkArgument ( negativeSign > 0 ) ; if ( negativeSign == this . negativeSign ) return this ; else return new MonetaryFormat ( negativeSign , positiveSign , zeroDigit , decimalMark , minDecimals , decim... | Set character to prefix negative values . |
33,813 | public MonetaryFormat positiveSign ( char positiveSign ) { checkArgument ( ! Character . isDigit ( positiveSign ) ) ; if ( positiveSign == this . positiveSign ) return this ; else return new MonetaryFormat ( negativeSign , positiveSign , zeroDigit , decimalMark , minDecimals , decimalGroups , shift , roundingMode , cod... | Set character to prefix positive values . A zero value means no sign is used in this case . For parsing a missing sign will always be interpreted as if the positive sign was used . |
33,814 | public MonetaryFormat digits ( char zeroDigit ) { if ( zeroDigit == this . zeroDigit ) return this ; else return new MonetaryFormat ( negativeSign , positiveSign , zeroDigit , decimalMark , minDecimals , decimalGroups , shift , roundingMode , codes , codeSeparator , codePrefixed ) ; } | Set character range to use for representing digits . It starts with the specified character representing zero . |
33,815 | public MonetaryFormat decimalMark ( char decimalMark ) { checkArgument ( ! Character . isDigit ( decimalMark ) ) ; checkArgument ( decimalMark > 0 ) ; if ( decimalMark == this . decimalMark ) return this ; else return new MonetaryFormat ( negativeSign , positiveSign , zeroDigit , decimalMark , minDecimals , decimalGrou... | Set character to use as the decimal mark . If the formatted value does not have any decimals no decimal mark is used either . |
33,816 | public MonetaryFormat shift ( int shift ) { if ( shift == this . shift ) return this ; else return new MonetaryFormat ( negativeSign , positiveSign , zeroDigit , decimalMark , minDecimals , decimalGroups , shift , roundingMode , codes , codeSeparator , codePrefixed ) ; } | Set number of digits to shift the decimal separator to the right coming from the standard BTC notation that was common pre - 2014 . Note this will change the currency code if enabled . |
33,817 | public MonetaryFormat roundingMode ( RoundingMode roundingMode ) { if ( roundingMode == this . roundingMode ) return this ; else return new MonetaryFormat ( negativeSign , positiveSign , zeroDigit , decimalMark , minDecimals , decimalGroups , shift , roundingMode , codes , codeSeparator , codePrefixed ) ; } | Set rounding mode to use when it becomes necessary . |
33,818 | public MonetaryFormat noCode ( ) { if ( codes == null ) return this ; else return new MonetaryFormat ( negativeSign , positiveSign , zeroDigit , decimalMark , minDecimals , decimalGroups , shift , roundingMode , null , codeSeparator , codePrefixed ) ; } | Don t display currency code when formatting . This configuration is not relevant for parsing . |
33,819 | public MonetaryFormat code ( int codeShift , String code ) { checkArgument ( codeShift >= 0 ) ; final String [ ] codes = null == this . codes ? new String [ MAX_DECIMALS ] : Arrays . copyOf ( this . codes , this . codes . length ) ; codes [ codeShift ] = code ; return new MonetaryFormat ( negativeSign , positiveSign , ... | Configure currency code for given decimal separator shift . This configuration is not relevant for parsing . |
33,820 | public MonetaryFormat codeSeparator ( char codeSeparator ) { checkArgument ( ! Character . isDigit ( codeSeparator ) ) ; checkArgument ( codeSeparator > 0 ) ; if ( codeSeparator == this . codeSeparator ) return this ; else return new MonetaryFormat ( negativeSign , positiveSign , zeroDigit , decimalMark , minDecimals ,... | Separator between currency code and formatted value . This configuration is not relevant for parsing . |
33,821 | public MonetaryFormat prefixCode ( ) { if ( codePrefixed ) return this ; else return new MonetaryFormat ( negativeSign , positiveSign , zeroDigit , decimalMark , minDecimals , decimalGroups , shift , roundingMode , codes , codeSeparator , true ) ; } | Prefix formatted output by currency code . This configuration is not relevant for parsing . |
33,822 | public MonetaryFormat postfixCode ( ) { if ( ! codePrefixed ) return this ; else return new MonetaryFormat ( negativeSign , positiveSign , zeroDigit , decimalMark , minDecimals , decimalGroups , shift , roundingMode , codes , codeSeparator , false ) ; } | Postfix formatted output with currency code . This configuration is not relevant for parsing . |
33,823 | public CharSequence format ( Monetary monetary ) { int maxDecimals = minDecimals ; if ( decimalGroups != null ) for ( int group : decimalGroups ) maxDecimals += group ; int smallestUnitExponent = monetary . smallestUnitExponent ( ) ; checkState ( maxDecimals <= smallestUnitExponent , "The maximum possible number of dec... | Format the given monetary value to a human readable form . |
33,824 | public String code ( ) { if ( codes == null ) return null ; if ( codes [ shift ] == null ) throw new NumberFormatException ( "missing code for shift: " + shift ) ; return codes [ shift ] ; } | Get currency code that will be used for current shift . |
33,825 | public static Path get ( String appName ) { final Path applicationDataDirectory = getPath ( appName ) ; try { Files . createDirectories ( applicationDataDirectory ) ; } catch ( IOException ioe ) { throw new RuntimeException ( "Couldn't find/create AppDataDirectory" , ioe ) ; } return applicationDataDirectory ; } | Get and create if necessary the Path to the application data directory . |
33,826 | public static DeterministicKey deriveThisOrNextChildKey ( DeterministicKey parent , int childNumber ) { int nAttempts = 0 ; ChildNumber child = new ChildNumber ( childNumber ) ; boolean isHardened = child . isHardened ( ) ; while ( nAttempts < MAX_CHILD_DERIVATION_ATTEMPTS ) { try { child = new ChildNumber ( child . nu... | Derives a key of the extended child number ie . with the 0x80000000 bit specifying whether to use hardened derivation or not . If derivation fails tries a next child . |
33,827 | public ScriptBuilder op ( int index , int opcode ) { checkArgument ( opcode > OP_PUSHDATA4 ) ; return addChunk ( index , new ScriptChunk ( opcode , null ) ) ; } | Adds the given opcode to the given index in the program |
33,828 | public ScriptBuilder number ( int index , long num ) { if ( num == - 1 ) { return op ( index , OP_1NEGATE ) ; } else if ( num >= 0 && num <= 16 ) { return smallNum ( index , ( int ) num ) ; } else { return bigNum ( index , num ) ; } } | Adds the given number to the given index in the program . Automatically uses shortest encoding possible . |
33,829 | public ScriptBuilder smallNum ( int index , int num ) { checkArgument ( num >= 0 , "Cannot encode negative numbers with smallNum" ) ; checkArgument ( num <= 16 , "Cannot encode numbers larger than 16 with smallNum" ) ; return addChunk ( index , new ScriptChunk ( Script . encodeToOpN ( num ) , null ) ) ; } | Adds the given number as a OP_N opcode to the given index in the program . Only handles values 0 - 16 inclusive . |
33,830 | protected ScriptBuilder bigNum ( int index , long num ) { final byte [ ] data ; if ( num == 0 ) { data = new byte [ 0 ] ; } else { Stack < Byte > result = new Stack < > ( ) ; final boolean neg = num < 0 ; long absvalue = Math . abs ( num ) ; while ( absvalue != 0 ) { result . push ( ( byte ) ( absvalue & 0xff ) ) ; abs... | Adds the given number as a push data chunk to the given index in the program . This is intended to use for negative numbers or values greater than 16 and although it will accept numbers in the range 0 - 16 inclusive the encoding would be considered non - standard . |
33,831 | public static Script createOutputScript ( Address to ) { if ( to instanceof LegacyAddress ) { ScriptType scriptType = to . getOutputScriptType ( ) ; if ( scriptType == ScriptType . P2PKH ) return createP2PKHOutputScript ( to . getHash ( ) ) ; else if ( scriptType == ScriptType . P2SH ) return createP2SHOutputScript ( t... | Creates a scriptPubKey that encodes payment to the given address . |
33,832 | public static Script createMultiSigInputScript ( List < TransactionSignature > signatures ) { List < byte [ ] > sigs = new ArrayList < > ( signatures . size ( ) ) ; for ( TransactionSignature signature : signatures ) { sigs . add ( signature . encodeToBitcoin ( ) ) ; } return createMultiSigInputScriptBytes ( sigs , nul... | Create a program that satisfies an OP_CHECKMULTISIG program . |
33,833 | public static BtcFormat getCoinInstance ( Locale locale , int scale , int ... groups ) { return getInstance ( COIN_SCALE , locale , scale , boxAsList ( groups ) ) ; } | Return a newly - constructed instance for the given locale that will format values in terms of bitcoins with the given minimum number of fractional decimal places . Optionally repeating integer arguments can be passed each indicating the size of an additional group of fractional decimal places to be used as necessary t... |
33,834 | public static BtcFormat getMilliInstance ( int scale , int ... groups ) { return getInstance ( MILLICOIN_SCALE , defaultLocale ( ) , scale , boxAsList ( groups ) ) ; } | Return a new millicoin - denominated formatter with the specified fractional decimal placing . The returned object will format and parse values according to the default locale and will format the fractional part of numbers with the given minimum number of fractional decimal places . Optionally repeating integer argumen... |
33,835 | public static BtcFormat getMilliInstance ( Locale locale , int scale , int ... groups ) { return getInstance ( MILLICOIN_SCALE , locale , scale , boxAsList ( groups ) ) ; } | Return a new millicoin - denominated formatter for the given locale with the specified fractional decimal placing . The returned object will format the fractional part of numbers with the given minimum number of fractional decimal places . Optionally repeating integer arguments can be passed each indicating the size of... |
33,836 | public static BtcFormat getMicroInstance ( int scale , int ... groups ) { return getInstance ( MICROCOIN_SCALE , defaultLocale ( ) , scale , boxAsList ( groups ) ) ; } | Return a new microcoin - denominated formatter with the specified fractional decimal placing . The returned object will format and parse values according to the default locale and will format the fractional part of numbers with the given minimum number of fractional decimal places . Optionally repeating integer argumen... |
33,837 | public static BtcFormat getMicroInstance ( Locale locale , int scale , int ... groups ) { return getInstance ( MICROCOIN_SCALE , locale , scale , boxAsList ( groups ) ) ; } | Return a new microcoin - denominated formatter for the given locale with the specified fractional decimal placing . The returned object will format the fractional part of numbers with the given minimum number of fractional decimal places . Optionally repeating integer arguments can be passed each indicating the size of... |
33,838 | public static BtcFormat getInstance ( int scale , int minDecimals , int ... groups ) { return getInstance ( scale , defaultLocale ( ) , minDecimals , boxAsList ( groups ) ) ; } | Return a new fixed - denomination formatter with the specified fractional decimal placing . The first argument specifies the denomination as the size of the shift from coin - denomination in increasingly - precise decimal places . The returned object will format and parse values according to the default locale and will... |
33,839 | public static BtcFormat getInstance ( int scale , Locale locale , int minDecimals , int ... groups ) { return getInstance ( scale , locale , minDecimals , boxAsList ( groups ) ) ; } | Return a new fixed - denomination formatter for the given locale with the specified fractional decimal placing . The first argument specifies the denomination as the size of the shift from coin - denomination in increasingly - precise decimal places . The third parameter is the minimum number of fractional decimal plac... |
33,840 | private static ImmutableList < Integer > setFormatterDigits ( DecimalFormat formatter , int min , int max ) { ImmutableList < Integer > ante = ImmutableList . of ( formatter . getMinimumFractionDigits ( ) , formatter . getMaximumFractionDigits ( ) ) ; formatter . setMinimumFractionDigits ( min ) ; formatter . setMaximu... | Sets the number of fractional decimal places to be displayed on the given NumberFormat object to the value of the given integer . |
33,841 | private static int calculateFractionPlaces ( BigDecimal unitCount , int scale , int minDecimals , List < Integer > fractionGroups ) { int places = minDecimals ; for ( int group : fractionGroups ) { places += group ; } int max = Math . min ( places , offSatoshis ( scale ) ) ; places = Math . min ( minDecimals , max ) ; ... | Return the number of fractional decimal places to be displayed when formatting the given number of monetary units of the denomination indicated by the given decimal scale value where 0 = coin 3 = millicoin and so on . |
33,842 | private static BigInteger inSatoshis ( Object qty ) { BigInteger satoshis ; if ( qty instanceof Long || qty instanceof Integer ) satoshis = BigInteger . valueOf ( ( ( Number ) qty ) . longValue ( ) ) ; else if ( qty instanceof BigInteger ) satoshis = ( BigInteger ) qty ; else if ( qty instanceof BigDecimal ) satoshis =... | Takes an object representing a bitcoin quantity of any type the client is permitted to pass us and return a BigInteger representing the number of satoshis having the equivalent value . |
33,843 | protected static void prefixUnitsIndicator ( DecimalFormat numberFormat , int scale ) { checkState ( Thread . holdsLock ( numberFormat ) ) ; DecimalFormatSymbols fs = numberFormat . getDecimalFormatSymbols ( ) ; setSymbolAndCode ( numberFormat , prefixSymbol ( fs . getCurrencySymbol ( ) , scale ) , prefixCode ( fs . ge... | Set both the currency symbol and code of the underlying mutable NumberFormat object according to the given denominational units scale factor . This is for formatting not parsing . |
33,844 | protected static String negify ( String pattern ) { if ( pattern . contains ( ";" ) ) return pattern ; else { if ( pattern . contains ( "-" ) ) throw new IllegalStateException ( "Positive pattern contains negative sign" ) ; return pattern + ";" + pattern . replaceFirst ( "^([^#0,.']*('[^']*')?)*" , "$0-" ) ; } } | Guarantee a formatting pattern has a subpattern for negative values . This method takes a pattern that may be missing a negative subpattern and returns the same pattern with a negative subpattern appended as needed . |
33,845 | synchronized PaymentChannelServer setConnectedHandler ( PaymentChannelServer connectedHandler , boolean override ) { if ( this . connectedHandler != null && ! override ) return this . connectedHandler ; this . connectedHandler = connectedHandler ; return connectedHandler ; } | Attempts to connect the given handler to this returning true if it is the new handler false if there was already one attached . |
33,846 | public static RuleViolation isOutputStandard ( TransactionOutput output ) { if ( output . getValue ( ) . compareTo ( MIN_ANALYSIS_NONDUST_OUTPUT ) < 0 ) return RuleViolation . DUST ; for ( ScriptChunk chunk : output . getScriptPubKey ( ) . getChunks ( ) ) { if ( chunk . isPushData ( ) && ! chunk . isShortestPossiblePus... | Checks the output to see if the script violates a standardness rule . Not complete . |
33,847 | public static RuleViolation isInputStandard ( TransactionInput input ) { for ( ScriptChunk chunk : input . getScriptSig ( ) . getChunks ( ) ) { if ( chunk . data != null && ! chunk . isShortestPossiblePushData ( ) ) return RuleViolation . SHORTEST_POSSIBLE_PUSHDATA ; if ( chunk . isPushData ( ) ) { ECDSASignature signa... | Checks if the given input passes some of the AreInputsStandard checks . Not complete . |
33,848 | public static SendRequest forTx ( Transaction tx ) { SendRequest req = new SendRequest ( ) ; req . tx = tx ; return req ; } | Simply wraps a pre - built incomplete transaction provided by you . |
33,849 | public static Image imageFromString ( String uri , int width , int height ) { return imageFromMatrix ( matrixFromString ( uri , width , height ) ) ; } | Create an Image from a Bitcoin URI |
33,850 | private static BitMatrix matrixFromString ( String uri , int width , int height ) { Writer qrWriter = new QRCodeWriter ( ) ; BitMatrix matrix ; try { matrix = qrWriter . encode ( uri , BarcodeFormat . QR_CODE , width , height ) ; } catch ( WriterException e ) { throw new RuntimeException ( e ) ; } return matrix ; } | Create a BitMatrix from a Bitcoin URI |
33,851 | private static Image imageFromMatrix ( BitMatrix matrix ) { int height = matrix . getHeight ( ) ; int width = matrix . getWidth ( ) ; WritableImage image = new WritableImage ( width , height ) ; for ( int y = 0 ; y < height ; y ++ ) { for ( int x = 0 ; x < width ; x ++ ) { Color color = matrix . get ( x , y ) ? Color .... | Create a JavaFX Image from a BitMatrix |
33,852 | public int getIndex ( ) { List < TransactionOutput > outputs = getParentTransaction ( ) . getOutputs ( ) ; for ( int i = 0 ; i < outputs . size ( ) ; i ++ ) { if ( outputs . get ( i ) == this ) return i ; } throw new IllegalStateException ( "Output linked to wrong parent transaction?" ) ; } | Gets the index of this output in the parent transaction or throws if this output is free standing . Iterates over the parents list to discover this . |
33,853 | public void markAsSpent ( TransactionInput input ) { checkState ( availableForSpending ) ; availableForSpending = false ; spentBy = input ; if ( parent != null ) if ( log . isDebugEnabled ( ) ) log . debug ( "Marked {}:{} as spent by {}" , getParentTransactionHash ( ) , getIndex ( ) , input ) ; else if ( log . isDebugE... | Sets this objects availableForSpending flag to false and the spentBy pointer to the given input . If the input is null it means this output was signed over to somebody else rather than one of our own keys . |
33,854 | public int getParentTransactionDepthInBlocks ( ) { if ( getParentTransaction ( ) != null ) { TransactionConfidence confidence = getParentTransaction ( ) . getConfidence ( ) ; if ( confidence . getConfidenceType ( ) == TransactionConfidence . ConfidenceType . BUILDING ) { return confidence . getDepthInBlocks ( ) ; } } r... | Returns the depth in blocks of the parent tx . |
33,855 | public TransactionOutput duplicateDetached ( ) { return new TransactionOutput ( params , null , Coin . valueOf ( value ) , Arrays . copyOf ( scriptBytes , scriptBytes . length ) ) ; } | Returns a copy of the output detached from its containing transaction if need be . |
33,856 | public boolean isSignatureValid ( ) { try { return ECKey . verify ( Sha256Hash . hashTwice ( content ) , signature , params . getAlertSigningKey ( ) ) ; } catch ( SignatureDecodeException e ) { return false ; } } | Returns true if the digital signature attached to the message verifies . Don t do anything with the alert if it doesn t verify because that would allow arbitrary attackers to spam your users . |
33,857 | protected final double curve ( final double v ) { switch ( easingMode . get ( ) ) { case EASE_IN : return baseCurve ( v ) ; case EASE_OUT : return 1 - baseCurve ( 1 - v ) ; case EASE_BOTH : if ( v <= 0.5 ) { return baseCurve ( 2 * v ) / 2 ; } else { return ( 2 - baseCurve ( 2 * ( 1 - v ) ) ) / 2 ; } } return baseCurve ... | Curves the function depending on the easing mode . |
33,858 | public final void bitcoinSerialize ( OutputStream stream ) throws IOException { if ( payload != null && length != UNKNOWN_LENGTH ) { stream . write ( payload , offset , length ) ; return ; } bitcoinSerializeToStream ( stream ) ; } | Serialize this message to the provided OutputStream using the bitcoin wire format . |
33,859 | private void readObject ( ObjectInputStream in ) throws IOException , ClassNotFoundException { in . defaultReadObject ( ) ; if ( null != params ) { this . serializer = params . getDefaultSerializer ( ) ; } } | Set the serializer for this message when deserialized by Java . |
33,860 | public Message deserialize ( ByteBuffer in ) throws ProtocolException , IOException { seekPastMagicBytes ( in ) ; BitcoinPacketHeader header = new BitcoinPacketHeader ( in ) ; return deserializePayload ( header , in ) ; } | Reads a message from the given ByteBuffer and returns it . |
33,861 | public AddressMessage makeAddressMessage ( byte [ ] payloadBytes , int length ) throws ProtocolException { return new AddressMessage ( params , payloadBytes , this , length ) ; } | Make an address message from the payload . Extension point for alternative serialization format support . |
33,862 | public Block makeBlock ( final byte [ ] payloadBytes , final int offset , final int length ) throws ProtocolException { return new Block ( params , payloadBytes , offset , this , length ) ; } | Make a block from the payload . Extension point for alternative serialization format support . |
33,863 | public InventoryMessage makeInventoryMessage ( byte [ ] payloadBytes , int length ) throws ProtocolException { return new InventoryMessage ( params , payloadBytes , this , length ) ; } | Make an inventory message from the payload . Extension point for alternative serialization format support . |
33,864 | protected void progress ( double pct , int blocksSoFar , Date date ) { log . info ( String . format ( Locale . US , "Chain download %d%% done with %d blocks to go, block date %s" , ( int ) pct , blocksSoFar , Utils . dateTimeFormat ( date ) ) ) ; } | Called when download progress is made . |
33,865 | public void initialize ( ) { Coin balance = Main . bitcoin . wallet ( ) . getBalance ( ) ; checkState ( ! balance . isZero ( ) ) ; new BitcoinAddressValidator ( Main . params , address , sendBtn ) ; new TextFieldValidator ( amountEdit , text -> ! WTUtils . didThrow ( ( ) -> checkState ( Coin . parseCoin ( text ) . comp... | Called by FXMLLoader |
33,866 | public byte [ ] encode ( ) { byte [ ] bytes ; switch ( sizeOf ( value ) ) { case 1 : return new byte [ ] { ( byte ) value } ; case 3 : bytes = new byte [ 3 ] ; bytes [ 0 ] = ( byte ) 253 ; Utils . uint16ToByteArrayLE ( ( int ) value , bytes , 1 ) ; return bytes ; case 5 : bytes = new byte [ 5 ] ; bytes [ 0 ] = ( byte )... | Encodes the value into its minimal representation . |
33,867 | public static Context getOrCreate ( NetworkParameters params ) { Context context ; try { context = get ( ) ; } catch ( IllegalStateException e ) { log . warn ( "Implicitly creating context. This is a migration step and this message will eventually go away." ) ; context = new Context ( params ) ; return context ; } if (... | A temporary internal shim designed to help us migrate internally in a way that doesn t wreck source compatibility . |
33,868 | protected void parseTransactions ( final int transactionsOffset ) throws ProtocolException { cursor = transactionsOffset ; optimalEncodingMessageSize = HEADER_SIZE ; if ( payload . length == cursor ) { transactionBytesValid = false ; return ; } int numTransactions = ( int ) readVarInt ( ) ; optimalEncodingMessageSize +... | Parse transactions from the block . |
33,869 | void writeHeader ( OutputStream stream ) throws IOException { if ( headerBytesValid && payload != null && payload . length >= offset + HEADER_SIZE ) { stream . write ( payload , offset , HEADER_SIZE ) ; return ; } Utils . uint32ToByteStreamLE ( version , stream ) ; stream . write ( prevBlockHash . getReversedBytes ( ) ... | default for testing |
33,870 | public byte [ ] bitcoinSerialize ( ) { if ( headerBytesValid && transactionBytesValid ) { Preconditions . checkNotNull ( payload , "Bytes should never be null if headerBytesValid && transactionBytesValid" ) ; if ( length == payload . length ) { return payload ; } else { byte [ ] buf = new byte [ length ] ; System . arr... | Special handling to check if we have a valid byte array for both header and transactions |
33,871 | private int guessTransactionsLength ( ) { if ( transactionBytesValid ) return payload . length - HEADER_SIZE ; if ( transactions == null ) return 0 ; int len = VarInt . sizeOf ( transactions . size ( ) ) ; for ( Transaction tx : transactions ) { len += tx . length == UNKNOWN_LENGTH ? 255 : tx . length ; } return len ; ... | Provides a reasonable guess at the byte length of the transactions part of the block . The returned value will be accurate in 99% of cases and in those cases where not will probably slightly oversize . |
33,872 | private Sha256Hash calculateHash ( ) { try { ByteArrayOutputStream bos = new UnsafeByteArrayOutputStream ( HEADER_SIZE ) ; writeHeader ( bos ) ; return Sha256Hash . wrapReversed ( Sha256Hash . hashTwice ( bos . toByteArray ( ) ) ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } | Calculates the block hash by serializing the block and hashing the resulting bytes . |
33,873 | public Block cloneAsHeader ( ) { Block block = new Block ( params , BLOCK_VERSION_GENESIS ) ; copyBitcoinHeaderTo ( block ) ; return block ; } | Returns a copy of the block but without any transactions . |
33,874 | protected final void copyBitcoinHeaderTo ( final Block block ) { block . nonce = nonce ; block . prevBlockHash = prevBlockHash ; block . merkleRoot = getMerkleRoot ( ) ; block . version = version ; block . time = time ; block . difficultyTarget = difficultyTarget ; block . transactions = null ; block . hash = getHash (... | Copy the block without transactions into the provided empty block . |
33,875 | public BigInteger getDifficultyTargetAsInteger ( ) throws VerificationException { BigInteger target = Utils . decodeCompactBits ( difficultyTarget ) ; if ( target . signum ( ) <= 0 || target . compareTo ( params . maxTarget ) > 0 ) throw new VerificationException ( "Difficulty target is bad: " + target . toString ( ) )... | Returns the difficulty target as a 256 bit value that can be compared to a SHA - 256 hash . Inside a block the target is represented using a compact form . If this form decodes to a value that is out of bounds an exception is thrown . |
33,876 | private void checkTransactions ( final int height , final EnumSet < VerifyFlag > flags ) throws VerificationException { if ( ! transactions . get ( 0 ) . isCoinBase ( ) ) throw new VerificationException ( "First tx is not coinbase" ) ; if ( flags . contains ( Block . VerifyFlag . HEIGHT_IN_COINBASE ) && height >= BLOCK... | Verify the transactions on a block . |
33,877 | public void verifyTransactions ( final int height , final EnumSet < VerifyFlag > flags ) throws VerificationException { if ( transactions . isEmpty ( ) ) throw new VerificationException ( "Block had no transactions" ) ; if ( this . getOptimalEncodingMessageSize ( ) > MAX_BLOCK_SIZE ) throw new VerificationException ( "... | Checks the block contents |
33,878 | public void verify ( final int height , final EnumSet < VerifyFlag > flags ) throws VerificationException { verifyHeader ( ) ; verifyTransactions ( height , flags ) ; } | Verifies both the header and that the transactions hash to the merkle root . |
33,879 | void addTransaction ( Transaction t , boolean runSanityChecks ) { unCacheTransactions ( ) ; if ( transactions == null ) { transactions = new ArrayList < > ( ) ; } t . setParent ( this ) ; if ( runSanityChecks && transactions . size ( ) == 0 && ! t . isCoinBase ( ) ) throw new RuntimeException ( "Attempted to add a non-... | Adds a transaction to this block with or without checking the sanity of doing so |
33,880 | public List < Transaction > getTransactions ( ) { return transactions == null ? null : ImmutableList . copyOf ( transactions ) ; } | Returns an immutable list of transactions held in this block or null if this object represents just a header . |
33,881 | public Block createNextBlock ( Address to , long version , long time , int blockHeight ) { return createNextBlock ( to , version , null , time , pubkeyForTesting , FIFTY_COINS , blockHeight ) ; } | Returns a solved block that builds on top of this one . This exists for unit tests . |
33,882 | public void close ( ) { lock . lock ( ) ; try { if ( writeTarget == null ) { closePending = true ; return ; } } finally { lock . unlock ( ) ; } writeTarget . closeConnection ( ) ; } | Closes the connection to the peer if one exists or immediately closes the connection as soon as it opens |
33,883 | private void exceptionCaught ( Exception e ) { PeerAddress addr = getAddress ( ) ; String s = addr == null ? "?" : addr . toString ( ) ; if ( e instanceof ConnectException || e instanceof IOException ) { log . info ( s + " - " + e . getMessage ( ) ) ; } else { log . warn ( s + " - " , e ) ; Thread . UncaughtExceptionHa... | Catch any exceptions logging them and then closing the channel . |
33,884 | public WalletAppKit setPeerNodes ( PeerAddress ... addresses ) { checkState ( state ( ) == State . NEW , "Cannot call after startup" ) ; this . peerAddresses = addresses ; return this ; } | Will only connect to the given addresses . Cannot be called after startup . |
33,885 | public WalletAppKit connectToLocalHost ( ) { try { final InetAddress localHost = InetAddress . getLocalHost ( ) ; return setPeerNodes ( new PeerAddress ( params , localHost , params . getPort ( ) ) ) ; } catch ( UnknownHostException e ) { throw new RuntimeException ( e ) ; } } | Will only connect to localhost . Cannot be called after startup . |
33,886 | public WalletAppKit setUserAgent ( String userAgent , String version ) { this . userAgent = checkNotNull ( userAgent ) ; this . version = checkNotNull ( version ) ; return this ; } | Sets the string that will appear in the subver field of the version message . |
33,887 | public boolean isChainFileLocked ( ) throws IOException { RandomAccessFile file2 = null ; try { File file = new File ( directory , filePrefix + ".spvchain" ) ; if ( ! file . exists ( ) ) return false ; if ( file . isDirectory ( ) ) return false ; file2 = new RandomAccessFile ( file , "rw" ) ; FileLock lock = file2 . ge... | Tests to see if the spvchain file has an operating system file lock on it . Useful for checking if your app is already running . If another copy of your app is running and you start the appkit anyway an exception will be thrown during the startup process . Returns false if the chain file does not exist or is a director... |
33,888 | protected synchronized void resetTimeout ( ) { if ( timeoutTask != null ) timeoutTask . cancel ( ) ; if ( timeoutMillis == 0 || ! timeoutEnabled ) return ; timeoutTask = new TimerTask ( ) { public void run ( ) { timeoutOccurred ( ) ; } } ; timeoutTimer . schedule ( timeoutTask , timeoutMillis ) ; } | Resets the current progress towards timeout to 0 . |
33,889 | public void add ( final long version ) { versionWindow [ versionWriteHead ++ ] = version ; if ( versionWriteHead == versionWindow . length ) { versionWriteHead = 0 ; } versionsStored ++ ; } | Add a new block version to the tally and return the count for that version within the window . |
33,890 | public Integer getCountAtOrAbove ( final long version ) { if ( versionsStored < versionWindow . length ) { return null ; } int count = 0 ; for ( int versionIdx = 0 ; versionIdx < versionWindow . length ; versionIdx ++ ) { if ( versionWindow [ versionIdx ] >= version ) { count ++ ; } } return count ; } | Get the count of blocks at or above the given version within the window . |
33,891 | public void initialize ( final BlockStore blockStore , final StoredBlock chainHead ) throws BlockStoreException { StoredBlock versionBlock = chainHead ; final Stack < Long > versions = new Stack < > ( ) ; versions . push ( versionBlock . getHeader ( ) . getVersion ( ) ) ; for ( int headOffset = 0 ; headOffset < version... | Initialize the version tally from the block store . Note this does not search backwards past the start of the block store so if starting from a checkpoint this may not fill the window . |
33,892 | private void putWithValidation ( String key , Object value ) throws BitcoinURIParseException { if ( parameterMap . containsKey ( key ) ) { throw new BitcoinURIParseException ( String . format ( Locale . US , "'%s' is duplicated, URI is invalid" , key ) ) ; } else { parameterMap . put ( key , value ) ; } } | Put the value against the key in the map checking for duplication . This avoids address field overwrite etc . |
33,893 | static String encodeURLString ( String stringToEncode ) { try { return java . net . URLEncoder . encode ( stringToEncode , "UTF-8" ) . replace ( "+" , ENCODED_SPACE_CHARACTER ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } } | Encode a string using URL encoding |
33,894 | public void crashAlert ( Stage stage , String crashMessage ) { messageLabel . setText ( "Unfortunately, we screwed up and the app crashed. Sorry about that!" ) ; detailsLabel . setText ( crashMessage ) ; cancelButton . setVisible ( false ) ; actionButton . setVisible ( false ) ; okButton . setOnAction ( actionEvent -> ... | Initialize this alert dialog for information about a crash . |
33,895 | private TransactionBroadcaster getBroadcaster ( ) { try { return broadcasterFuture . get ( MAX_SECONDS_TO_WAIT_FOR_BROADCASTER_TO_BE_SET , TimeUnit . SECONDS ) ; } catch ( InterruptedException e ) { throw new RuntimeException ( e ) ; } catch ( ExecutionException e ) { throw new RuntimeException ( e ) ; } catch ( Timeou... | If the broadcaster has not been set for MAX_SECONDS_TO_WAIT_FOR_BROADCASTER_TO_BE_SET seconds then the programmer probably forgot to set it and we should throw exception . |
33,896 | public static int calcSigHashValue ( Transaction . SigHash mode , boolean anyoneCanPay ) { Preconditions . checkArgument ( SigHash . ALL == mode || SigHash . NONE == mode || SigHash . SINGLE == mode ) ; int sighashFlags = mode . value ; if ( anyoneCanPay ) sighashFlags |= Transaction . SigHash . ANYONECANPAY . value ; ... | Calculates the byte used in the protocol to represent the combination of mode and anyoneCanPay . |
33,897 | public static boolean isEncodingCanonical ( byte [ ] signature ) { if ( signature . length == 0 ) return true ; if ( signature . length < 9 || signature . length > 73 ) return false ; int hashType = ( signature [ signature . length - 1 ] & 0xff ) & ~ Transaction . SigHash . ANYONECANPAY . value ; if ( hashType < Transa... | Returns true if the given signature is has canonical encoding and will thus be accepted as standard by Bitcoin Core . DER and the SIGHASH encoding allow for quite some flexibility in how the same structures are encoded and this can open up novel attacks in which a man in the middle takes a transaction and then changes ... |
33,898 | public byte [ ] encodeToBitcoin ( ) { try { ByteArrayOutputStream bos = derByteStream ( ) ; bos . write ( sighashFlags ) ; return bos . toByteArray ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } | What we get back from the signer are the two components of a signature r and s . To get a flat byte stream of the type used by Bitcoin we have to encode them using DER encoding which is just a way to pack the two components into a structure and then we append a byte to the end for the sighash flags . |
33,899 | public static TransactionSignature decodeFromBitcoin ( byte [ ] bytes , boolean requireCanonicalEncoding , boolean requireCanonicalSValue ) throws SignatureDecodeException , VerificationException { if ( requireCanonicalEncoding && ! isEncodingCanonical ( bytes ) ) throw new VerificationException . NoncanonicalSignature... | Returns a decoded signature . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.