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 . newArrayList ( requiredStates ) , currentState ) ) ; } | 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 , newState ) ) ; } } | 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 [ i ] |= filter . data [ i ] ; } else { this . data = new byte [ ] { ( byte ) 0xff } ; } } | 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 ( ) / 8.0 ) ] ; for ( int i = 0 ; i < txns . size ( ) ; i ++ ) { Transaction tx = txns . get ( i ) ; txHashes . add ( tx . getTxId ( ) ) ; if ( applyAndUpdate ( tx ) ) { Utils . setBitLE ( bits , i ) ; matched . add ( tx ) ; } } PartialMerkleTree pmt = PartialMerkleTree . buildFromLeaves ( block . getParams ( ) , bits , txHashes ) ; FilteredBlock filteredBlock = new FilteredBlock ( block . getParams ( ) , block . cloneAsHeader ( ) , pmt ) ; for ( Transaction transaction : matched ) filteredBlock . provideTransaction ( transaction ) ; return filteredBlock ; } | 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 operation . The returned filtered block already has the matched transactions associated with it . |
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 ) ; try { if ( controller != null ) controller . getClass ( ) . getField ( "overlayUI" ) . set ( controller , pair ) ; } catch ( IllegalAccessException | NoSuchFieldException ignored ) { ignored . printStackTrace ( ) ; } pair . show ( ) ; return pair ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } | 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 = ( time + 0.0 ) / ( wallTimeNanos + 0.0 ) ; log . info ( name + " c:" + calls + " r:" + time + " a:" + average + " p:" + String . format ( "%.2f" , proportion ) ) ; } double dbproportion = ( dbtime + 0.0 ) / ( wallTimeNanos + 0.0 ) ; double hitrate = ( hit + 0.0 ) / ( hit + miss + 0.0 ) ; log . info ( "Cache size:" + utxoCache . size ( ) + " hit:" + hit + " miss:" + miss + " rate:" + String . format ( "%.2f" , hitrate ) ) ; bloom . printStat ( ) ; log . info ( "hasTxOut call:" + hasCall + " True:" + hasTrue + " False:" + hasFalse ) ; log . info ( "Wall:" + totalStopwatch + " percent:" + String . format ( "%.2f" , dbproportion ) ) ; String stats = db . getProperty ( "leveldb.stats" ) ; System . out . println ( stats ) ; } | 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 , decimalGroups , shift , roundingMode , codes , codeSeparator , codePrefixed ) ; } | 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 , codes , codeSeparator , codePrefixed ) ; } | 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 , decimalGroups , shift , roundingMode , codes , codeSeparator , codePrefixed ) ; } | 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 , zeroDigit , decimalMark , minDecimals , decimalGroups , shift , roundingMode , codes , codeSeparator , codePrefixed ) ; } | 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 , decimalGroups , shift , roundingMode , codes , codeSeparator , codePrefixed ) ; } | 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 decimals (%s) cannot exceed %s." , maxDecimals , smallestUnitExponent ) ; long satoshis = Math . abs ( monetary . getValue ( ) ) ; long precisionDivisor = checkedPow ( 10 , smallestUnitExponent - shift - maxDecimals ) ; satoshis = checkedMultiply ( divide ( satoshis , precisionDivisor , roundingMode ) , precisionDivisor ) ; long shiftDivisor = checkedPow ( 10 , smallestUnitExponent - shift ) ; long numbers = satoshis / shiftDivisor ; long decimals = satoshis % shiftDivisor ; String decimalsStr = String . format ( Locale . US , "%0" + ( smallestUnitExponent - shift ) + "d" , decimals ) ; StringBuilder str = new StringBuilder ( decimalsStr ) ; while ( str . length ( ) > minDecimals && str . charAt ( str . length ( ) - 1 ) == '0' ) str . setLength ( str . length ( ) - 1 ) ; int i = minDecimals ; if ( decimalGroups != null ) { for ( int group : decimalGroups ) { if ( str . length ( ) > i && str . length ( ) < i + group ) { while ( str . length ( ) < i + group ) str . append ( '0' ) ; break ; } i += group ; } } if ( str . length ( ) > 0 ) str . insert ( 0 , decimalMark ) ; str . insert ( 0 , numbers ) ; if ( monetary . getValue ( ) < 0 ) str . insert ( 0 , negativeSign ) ; else if ( positiveSign != 0 ) str . insert ( 0 , positiveSign ) ; if ( codes != null ) { if ( codePrefixed ) { str . insert ( 0 , codeSeparator ) ; str . insert ( 0 , code ( ) ) ; } else { str . append ( codeSeparator ) ; str . append ( code ( ) ) ; } } if ( zeroDigit != '0' ) { int offset = zeroDigit - '0' ; for ( int d = 0 ; d < str . length ( ) ; d ++ ) { char c = str . charAt ( d ) ; if ( Character . isDigit ( c ) ) str . setCharAt ( d , ( char ) ( c + offset ) ) ; } } return str ; } | 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 . num ( ) + nAttempts , isHardened ) ; return deriveChildKey ( parent , child ) ; } catch ( HDDerivationException ignore ) { } nAttempts ++ ; } throw new HDDerivationException ( "Maximum number of child derivation attempts reached, this is probably an indication of a bug." ) ; } | 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 ) ) ; absvalue >>= 8 ; } if ( ( result . peek ( ) & 0x80 ) != 0 ) { result . push ( ( byte ) ( neg ? 0x80 : 0 ) ) ; } else if ( neg ) { result . push ( ( byte ) ( result . pop ( ) | 0x80 ) ) ; } data = new byte [ result . size ( ) ] ; for ( int byteIdx = 0 ; byteIdx < data . length ; byteIdx ++ ) { data [ byteIdx ] = result . get ( byteIdx ) ; } } return addChunk ( index , new ScriptChunk ( data . length , data ) ) ; } | 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 ( to . getHash ( ) ) ; else throw new IllegalStateException ( "Cannot handle " + scriptType ) ; } else if ( to instanceof SegwitAddress ) { ScriptBuilder builder = new ScriptBuilder ( ) ; SegwitAddress toSegwit = ( SegwitAddress ) to ; builder . smallNum ( toSegwit . getWitnessVersion ( ) ) ; builder . data ( toSegwit . getWitnessProgram ( ) ) ; return builder . build ( ) ; } else { throw new IllegalStateException ( "Cannot handle " + to ) ; } } | 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 , null ) ; } | 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 to avoid rounding to a limiting precision of satoshis . |
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 arguments can be passed each indicating the size of an additional group of fractional decimal places to be used as necessary to avoid rounding to a limiting precision of satoshis . |
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 an additional group of fractional decimal places to be used as necessary to avoid rounding to a limiting precision of satoshis . |
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 arguments can be passed each indicating the size of an additional group of fractional decimal places to be used as necessary to avoid rounding to a limiting precision of satoshis . |
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 an additional group of fractional decimal places to be used as necessary to avoid rounding to a limiting precision of satoshis . |
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 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 an additional group of fractional decimal places to be used as necessary to avoid rounding to a limiting precision of satoshis . |
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 places to use followed by optional repeating integer parameters each specifying the size of an additional group of fractional decimal places to use as necessary to avoid rounding down to a maximum precision of satoshis . |
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 . setMaximumFractionDigits ( max ) ; return ante ; } | 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 ) ; for ( int group : fractionGroups ) { if ( unitCount . setScale ( places , HALF_UP ) . compareTo ( unitCount . setScale ( max , HALF_UP ) ) == 0 ) break ; places += group ; if ( places > max ) places = max ; } return places ; } | 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 = ( ( BigDecimal ) qty ) . movePointRight ( Coin . SMALLEST_UNIT_EXPONENT ) . setScale ( 0 , BigDecimal . ROUND_HALF_UP ) . unscaledValue ( ) ; else if ( qty instanceof Coin ) satoshis = BigInteger . valueOf ( ( ( Coin ) qty ) . value ) ; else throw new IllegalArgumentException ( "Cannot format a " + qty . getClass ( ) . getSimpleName ( ) + " as a Bicoin value" ) ; return 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 . getInternationalCurrencySymbol ( ) , scale ) ) ; } | 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 . isShortestPossiblePushData ( ) ) return RuleViolation . SHORTEST_POSSIBLE_PUSHDATA ; } return RuleViolation . NONE ; } | 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 signature ; try { signature = ECKey . ECDSASignature . decodeFromDER ( chunk . data ) ; } catch ( SignatureDecodeException x ) { signature = null ; } if ( signature != null ) { if ( ! TransactionSignature . isEncodingCanonical ( chunk . data ) ) return RuleViolation . SIGNATURE_CANONICAL_ENCODING ; if ( ! signature . isCanonical ( ) ) return RuleViolation . SIGNATURE_CANONICAL_ENCODING ; } } } return RuleViolation . NONE ; } | 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 . BLACK : Color . WHITE ; image . getPixelWriter ( ) . setColor ( x , y , color ) ; } } return image ; } | 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 . isDebugEnabled ( ) ) log . debug ( "Marked floating output as spent by {}" , input ) ; } | 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 ( ) ; } } return - 1 ; } | 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 ( v ) ; } | 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 ) . compareTo ( balance ) <= 0 ) ) ) ; amountEdit . setText ( balance . toPlainString ( ) ) ; address . setPromptText ( Address . fromKey ( Main . params , new ECKey ( ) , Main . PREFERRED_OUTPUT_SCRIPT_TYPE ) . toString ( ) ) ; } | 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 ) 254 ; Utils . uint32ToByteArrayLE ( value , bytes , 1 ) ; return bytes ; default : bytes = new byte [ 9 ] ; bytes [ 0 ] = ( byte ) 255 ; Utils . int64ToByteArrayLE ( value , bytes , 1 ) ; return bytes ; } } | 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 ( context . getParams ( ) != params ) throw new IllegalStateException ( "Context does not match implicit network params: " + context . getParams ( ) + " vs " + params ) ; return context ; } | 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 += VarInt . sizeOf ( numTransactions ) ; transactions = new ArrayList < > ( Math . min ( numTransactions , Utils . MAX_INITIAL_ARRAY_LENGTH ) ) ; for ( int i = 0 ; i < numTransactions ; i ++ ) { Transaction tx = new Transaction ( params , payload , cursor , this , serializer , UNKNOWN_LENGTH , null ) ; tx . getConfidence ( ) . setSource ( TransactionConfidence . Source . NETWORK ) ; transactions . add ( tx ) ; cursor += tx . getMessageSize ( ) ; optimalEncodingMessageSize += tx . getOptimalEncodingMessageSize ( ) ; } transactionBytesValid = serializer . isParseRetainMode ( ) ; } | 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 ( ) ) ; stream . write ( getMerkleRoot ( ) . getReversedBytes ( ) ) ; Utils . uint32ToByteStreamLE ( time , stream ) ; Utils . uint32ToByteStreamLE ( difficultyTarget , stream ) ; Utils . uint32ToByteStreamLE ( nonce , stream ) ; } | 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 . arraycopy ( payload , offset , buf , 0 , length ) ; return buf ; } } ByteArrayOutputStream stream = new UnsafeByteArrayOutputStream ( length == UNKNOWN_LENGTH ? HEADER_SIZE + guessTransactionsLength ( ) : length ) ; try { writeHeader ( stream ) ; writeTransactions ( stream ) ; } catch ( IOException e ) { } return stream . toByteArray ( ) ; } | 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 ( ) ) ; return target ; } | 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_HEIGHT_GENESIS ) { transactions . get ( 0 ) . checkCoinBaseHeight ( height ) ; } for ( int i = 1 ; i < transactions . size ( ) ; i ++ ) { if ( transactions . get ( i ) . isCoinBase ( ) ) throw new VerificationException ( "TX " + i + " is coinbase when it should not be." ) ; } } | 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 ( "Block larger than MAX_BLOCK_SIZE" ) ; checkTransactions ( height , flags ) ; checkMerkleRoot ( ) ; checkSigOps ( ) ; for ( Transaction transaction : transactions ) transaction . verify ( ) ; } | 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-coinbase transaction as the first transaction: " + t ) ; else if ( runSanityChecks && transactions . size ( ) > 0 && t . isCoinBase ( ) ) throw new RuntimeException ( "Attempted to add a coinbase transaction when there already is one: " + t ) ; transactions . add ( t ) ; adjustLength ( transactions . size ( ) , t . length ) ; merkleRoot = null ; hash = null ; } | 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 . UncaughtExceptionHandler handler = Threading . uncaughtExceptionHandler ; if ( handler != null ) handler . uncaughtException ( Thread . currentThread ( ) , e ) ; } close ( ) ; } | 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 . getChannel ( ) . tryLock ( ) ; if ( lock == null ) return true ; lock . release ( ) ; return false ; } finally { if ( file2 != null ) file2 . close ( ) ; } } | 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 directory . |
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 < versionWindow . length ; headOffset ++ ) { versionBlock = versionBlock . getPrev ( blockStore ) ; if ( null == versionBlock ) { break ; } versions . push ( versionBlock . getHeader ( ) . getVersion ( ) ) ; } while ( ! versions . isEmpty ( ) ) { add ( versions . pop ( ) ) ; } } | 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 -> stage . close ( ) ) ; } | 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 ( TimeoutException e ) { String err = "Transaction broadcaster not set" ; log . error ( err ) ; throw new RuntimeException ( err , e ) ; } } | 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 ; return sighashFlags ; } | 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 < Transaction . SigHash . ALL . value || hashType > Transaction . SigHash . SINGLE . value ) return false ; if ( ( signature [ 0 ] & 0xff ) != 0x30 || ( signature [ 1 ] & 0xff ) != signature . length - 3 ) return false ; int lenR = signature [ 3 ] & 0xff ; if ( 5 + lenR >= signature . length || lenR == 0 ) return false ; int lenS = signature [ 5 + lenR ] & 0xff ; if ( lenR + lenS + 7 != signature . length || lenS == 0 ) return false ; if ( signature [ 4 - 2 ] != 0x02 || ( signature [ 4 ] & 0x80 ) == 0x80 ) return false ; if ( lenR > 1 && signature [ 4 ] == 0x00 && ( signature [ 4 + 1 ] & 0x80 ) != 0x80 ) return false ; if ( signature [ 6 + lenR - 2 ] != 0x02 || ( signature [ 6 + lenR ] & 0x80 ) == 0x80 ) return false ; if ( lenS > 1 && signature [ 6 + lenR ] == 0x00 && ( signature [ 6 + lenR + 1 ] & 0x80 ) != 0x80 ) return false ; return true ; } | 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 its signature such that the transaction hash is different but it s still valid . This can confuse wallets and generally violates people s mental model of how Bitcoin should work thus non - canonical signatures are now not relayed by default . |
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 ( ) ; ECKey . ECDSASignature sig = ECKey . ECDSASignature . decodeFromDER ( bytes ) ; if ( requireCanonicalSValue && ! sig . isCanonical ( ) ) throw new VerificationException ( "S-value is not canonical." ) ; return new TransactionSignature ( sig . r , sig . s , bytes [ bytes . length - 1 ] ) ; } | Returns a decoded signature . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.