idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
24,400
def generate ( num , prompt_default = True ) : p = Problem ( num ) problem_text = p . text msg = "Generate file for problem %i?" % num click . confirm ( msg , default = prompt_default , abort = True ) if p . glob : filename = str ( p . file ) msg = '"{}" already exists. Overwrite?' . format ( filename ) click . confirm...
Generates Python file for a problem .
24,401
def preview ( num ) : problem_text = Problem ( num ) . text click . secho ( "Project Euler Problem %i" % num , bold = True ) click . echo ( problem_text )
Prints the text of a problem .
24,402
def skip ( num ) : click . echo ( "Current problem is problem %i." % num ) generate ( num + 1 , prompt_default = False ) Problem ( num ) . file . change_suffix ( '-skipped' )
Generates Python file for the next problem .
24,403
def verify ( num , filename = None , exit = True ) : p = Problem ( num ) filename = filename or p . filename ( ) if not os . path . isfile ( filename ) : if p . glob : filename = str ( p . file ) else : click . secho ( 'No file found for problem %i.' % p . num , fg = 'red' ) sys . exit ( 1 ) solution = p . solution cli...
Verifies the solution to a problem .
24,404
def verify_all ( num ) : keys = ( 'correct' , 'incorrect' , 'error' , 'skipped' , 'missing' ) symbols = ( 'C' , 'I' , 'E' , 'S' , '.' ) colours = ( 'green' , 'red' , 'yellow' , 'cyan' , 'white' ) status = OrderedDict ( ( key , click . style ( symbol , fg = colour , bold = True ) ) for key , symbol , colour in zip ( key...
Verifies all problem files in the current directory and prints an overview of the status of each problem .
24,405
def euler_options ( fn ) : euler_functions = cheat , generate , preview , skip , verify , verify_all for option in reversed ( euler_functions ) : name , docstring = option . __name__ , option . __doc__ kwargs = { 'flag_value' : option , 'help' : docstring } flag = '--%s' % name . replace ( '_' , '-' ) flags = [ flag ] ...
Decorator to link CLI options with their appropriate functions
24,406
def main ( option , problem ) : if problem == 0 or option in { skip , verify_all } : files = problem_glob ( ) problem = max ( file . num for file in files ) if files else 0 if problem == 0 : if option not in { cheat , preview , verify_all } : msg = "No Project Euler files found in the current directory." click . echo (...
Python - based Project Euler command line tool .
24,407
def start ( self , * args , ** kwargs ) : if args : LOG . debug ( "args: %s" % str ( args ) ) if kwargs : LOG . debug ( "kwargs: %s" % str ( kwargs ) ) try : self . _server . start ( ) self . _server . proxyInit ( ) return True except Exception as err : LOG . critical ( "Failed to start server" ) LOG . debug ( str ( er...
Start the server thread if it wasn t created with autostart = True .
24,408
def stop ( self , * args , ** kwargs ) : if args : LOG . debug ( "args: %s" % str ( args ) ) if kwargs : LOG . debug ( "kwargs: %s" % str ( kwargs ) ) try : self . _server . stop ( ) self . _server = None self . devices . clear ( ) self . devices_all . clear ( ) self . devices_raw . clear ( ) self . devices_raw_dict . ...
Stop the server thread .
24,409
def getMetadata ( self , remote , address , key ) : if self . _server is not None : return self . _server . getAllMetadata ( remote , address , key )
Get metadata of device
24,410
def get_hs_color ( self ) : hm_color = self . getCachedOrUpdatedValue ( "COLOR" , channel = self . _color_channel ) if hm_color >= 200 : return 0 , 0 return hm_color / 200 , 1
Return the color of the light as HSV color without the value component for the brightness .
24,411
def set_hs_color ( self , hue : float , saturation : float ) : self . turn_off_effect ( ) if saturation < 0.1 : hm_color = 200 else : hm_color = int ( round ( max ( min ( hue , 1 ) , 0 ) * 199 ) ) self . setValue ( key = "COLOR" , channel = self . _color_channel , value = hm_color )
Set a fixed color and also turn off effects in order to see the color .
24,412
def get_effect ( self ) -> str : effect_value = self . getCachedOrUpdatedValue ( "PROGRAM" , channel = self . _effect_channel ) try : return self . _light_effect_list [ effect_value ] except IndexError : LOG . error ( "Unexpected color effect returned by CCU" ) return "Unknown"
Return the current color change program of the light .
24,413
def set_effect ( self , effect_name : str ) : try : effect_index = self . _light_effect_list . index ( effect_name ) except ValueError : LOG . error ( "Trying to set unknown light effect" ) return False return self . setValue ( key = "PROGRAM" , channel = self . _effect_channel , value = effect_index )
Sets the color change program of the light .
24,414
def make_http_credentials ( username = None , password = None ) : credentials = '' if username is None : return credentials if username is not None : if ':' in username : return credentials credentials += username if credentials and password is not None : credentials += ":%s" % password return "%s@" % credentials
Build auth part for api_url .
24,415
def build_api_url ( host = REMOTES [ 'default' ] [ 'ip' ] , port = REMOTES [ 'default' ] [ 'port' ] , path = REMOTES [ 'default' ] [ 'path' ] , username = None , password = None , ssl = False ) : credentials = make_http_credentials ( username , password ) scheme = 'http' if not path : path = '' if path and not path . s...
Build API URL from components .
24,416
def createDeviceObjects ( self , interface_id ) : global WORKING WORKING = True remote = interface_id . split ( '-' ) [ - 1 ] LOG . debug ( "RPCFunctions.createDeviceObjects: iterating interface_id = %s" % ( remote , ) ) for dev in self . _devices_raw [ remote ] : if not dev [ 'PARENT' ] : if dev [ 'ADDRESS' ] not in s...
Transform the raw device descriptions into instances of devicetypes . generic . HMDevice or availabe subclass .
24,417
def event ( self , interface_id , address , value_key , value ) : LOG . debug ( "RPCFunctions.event: interface_id = %s, address = %s, value_key = %s, value = %s" % ( interface_id , address , value_key . upper ( ) , str ( value ) ) ) self . devices_all [ interface_id . split ( '-' ) [ - 1 ] ] [ address ] . event ( inter...
If a device emits some sort event we will handle it here .
24,418
def __request ( self , * args , ** kwargs ) : with self . lock : parent = xmlrpc . client . ServerProxy return parent . _ServerProxy__request ( self , * args , ** kwargs )
Call method on server side
24,419
def parseCCUSysVar ( self , data ) : if data [ 'type' ] == 'LOGIC' : return data [ 'name' ] , data [ 'value' ] == 'true' elif data [ 'type' ] == 'NUMBER' : return data [ 'name' ] , float ( data [ 'value' ] ) elif data [ 'type' ] == 'LIST' : return data [ 'name' ] , int ( data [ 'value' ] ) else : return data [ 'name' ]...
Helper to parse type of system variables of CCU
24,420
def jsonRpcLogin ( self , remote ) : session = False try : params = { "username" : self . remotes [ remote ] [ 'username' ] , "password" : self . remotes [ remote ] [ 'password' ] } response = self . _rpcfunctions . jsonRpcPost ( self . remotes [ remote ] [ 'ip' ] , self . remotes [ remote ] . get ( 'jsonport' , DEFAUL...
Login to CCU and return session
24,421
def jsonRpcLogout ( self , remote , session ) : logout = False try : params = { "_session_id_" : session } response = self . _rpcfunctions . jsonRpcPost ( self . remotes [ remote ] [ 'ip' ] , self . remotes [ remote ] . get ( 'jsonport' , DEFAULT_JSONPORT ) , "Session.logout" , params ) if response [ 'error' ] is None ...
Logout of CCU
24,422
def homegearCheckInit ( self , remote ) : rdict = self . remotes . get ( remote ) if not rdict : return False if rdict . get ( 'type' ) != BACKEND_HOMEGEAR : return False try : interface_id = "%s-%s" % ( self . _interface_id , remote ) return self . proxies [ interface_id ] . clientServerInitialized ( interface_id ) ex...
Check if proxy is still initialized
24,423
def set_ontime ( self , ontime ) : try : ontime = float ( ontime ) except Exception as err : LOG . debug ( "SwitchPowermeter.set_ontime: Exception %s" % ( err , ) ) return False self . actionNodeData ( "ON_TIME" , ontime )
Set duration th switch stays on when toggled .
24,424
def event ( self , interface_id , key , value ) : LOG . info ( "HMGeneric.event: address=%s, interface_id=%s, key=%s, value=%s" % ( self . _ADDRESS , interface_id , key , value ) ) self . _VALUES [ key ] = value for callback in self . _eventcallbacks : LOG . debug ( "HMGeneric.event: Using callback %s " % str ( callbac...
Handle the event received by server .
24,425
def getParamsetDescription ( self , paramset ) : try : self . _PARAMSET_DESCRIPTIONS [ paramset ] = self . _proxy . getParamsetDescription ( self . _ADDRESS , paramset ) except Exception as err : LOG . error ( "HMGeneric.getParamsetDescription: Exception: " + str ( err ) ) return False
Descriptions for paramsets are available to determine what can be don with the device .
24,426
def updateParamset ( self , paramset ) : try : if paramset : if self . _proxy : returnset = self . _proxy . getParamset ( self . _ADDRESS , paramset ) if returnset : self . _paramsets [ paramset ] = returnset if self . PARAMSETS : if self . PARAMSETS . get ( PARAMSET_VALUES ) : self . _VALUES [ PARAM_UNREACH ] = self ....
Devices should not update their own paramsets . They rely on the state of the server . Hence we pull the specified paramset .
24,427
def updateParamsets ( self ) : try : for ps in self . _PARAMSETS : self . updateParamset ( ps ) return True except Exception as err : LOG . error ( "HMGeneric.updateParamsets: Exception: " + str ( err ) ) return False
Devices should update their own paramsets . They rely on the state of the server . Hence we pull all paramsets .
24,428
def putParamset ( self , paramset , data = { } ) : try : if paramset in self . _PARAMSETS and data : self . _proxy . putParamset ( self . _ADDRESS , paramset , data ) self . updateParamsets ( ) return True else : return False except Exception as err : LOG . error ( "HMGeneric.putParamset: Exception: " + str ( err ) ) r...
Some devices act upon changes to paramsets . A putted paramset must not contain all keys available in the specified paramset just the ones which are writable and should be changed .
24,429
def getCachedOrUpdatedValue ( self , key ) : try : return self . _VALUES [ key ] except KeyError : return self . getValue ( key )
Gets the device s value with the given key .
24,430
def getCachedOrUpdatedValue ( self , key , channel = None ) : if channel : return self . _hmchannels [ channel ] . getCachedOrUpdatedValue ( key ) try : return self . _VALUES [ key ] except KeyError : value = self . _VALUES [ key ] = self . getValue ( key ) return value
Gets the channel s value with the given key .
24,431
def UNREACH ( self ) : if self . _VALUES . get ( PARAM_UNREACH , False ) : return True else : for device in self . _hmchannels . values ( ) : if device . UNREACH : return True return False
Returns true if the device or any children is not reachable
24,432
def getAttributeData ( self , name , channel = None ) : return self . _getNodeData ( name , self . _ATTRIBUTENODE , channel )
Returns a attribut
24,433
def getBinaryData ( self , name , channel = None ) : return self . _getNodeData ( name , self . _BINARYNODE , channel )
Returns a binary node
24,434
def set_temperature ( self , target_temperature ) : try : target_temperature = float ( target_temperature ) except Exception as err : LOG . debug ( "Thermostat.set_temperature: Exception %s" % ( err , ) ) return False self . writeNodeData ( "SET_TEMPERATURE" , target_temperature )
Set the target temperature .
24,435
def stop ( self ) : LOG . info ( "Shutting down server" ) self . server . shutdown ( ) LOG . debug ( "ServerThread.stop: Stopping ServerThread" ) self . server . server_close ( ) LOG . info ( "Server stopped" )
Shut down our XML - RPC server .
24,436
def heirarchical_help ( shovel , prefix ) : result = [ ] tuples = heirarchical_helper ( shovel , prefix ) if not tuples : return '' longest = max ( len ( name + ' ' * level ) for name , _ , level in tuples ) fmt = '%%%is => %%-50s' % longest for name , docstring , level in tuples : if docstring == None : result . ap...
Given a shovel of tasks display a heirarchical list of the tasks
24,437
def shovel_help ( shovel , * names ) : if not len ( names ) : return heirarchical_help ( shovel , '' ) else : for name in names : task = shovel [ name ] if isinstance ( task , Shovel ) : return heirarchical_help ( task , name ) else : return task . help ( )
Return a string about help with the tasks or lists tasks available
24,438
def load ( cls , path , base = None ) : obj = cls ( ) obj . read ( path , base ) return obj
Either load a path and return a shovel object or return None
24,439
def extend ( self , tasks ) : self . _tasks . extend ( tasks ) for task in tasks : current = self . map modules = task . fullname . split ( '.' ) for module in modules [ : - 1 ] : if not isinstance ( current [ module ] , Shovel ) : logger . warn ( 'Overriding task %s with a module' % current [ module ] . file ) shovel ...
Add tasks to this particular shovel
24,440
def read ( self , path , base = None ) : if base == None : base = os . getcwd ( ) absolute = os . path . abspath ( path ) if os . path . isfile ( absolute ) : logger . info ( 'Loading %s' % absolute ) self . extend ( Task . load ( path , base ) ) elif os . path . isdir ( absolute ) : tasks = [ ] for root , _ , files in...
Import some tasks
24,441
def keys ( self ) : keys = [ ] for key , value in self . map . items ( ) : if isinstance ( value , Shovel ) : keys . extend ( [ key + '.' + k for k in value . keys ( ) ] ) else : keys . append ( key ) return sorted ( keys )
Return all valid keys
24,442
def items ( self ) : pairs = [ ] for key , value in self . map . items ( ) : if isinstance ( value , Shovel ) : pairs . extend ( [ ( key + '.' + k , v ) for k , v in value . items ( ) ] ) else : pairs . append ( ( key , value ) ) return sorted ( pairs )
Return a list of tuples of all the keys and tasks
24,443
def tasks ( self , name ) : found = self [ name ] if isinstance ( found , Shovel ) : return [ v for _ , v in found . items ( ) ] return [ found ]
Get all the tasks that match a name
24,444
def make ( cls , obj ) : try : cls . _cache . append ( Task ( obj ) ) except Exception : logger . exception ( 'Unable to make task for %s' % repr ( obj ) )
Given a callable object return a new callable object
24,445
def load ( cls , path , base = None ) : base = base or os . getcwd ( ) absolute = os . path . abspath ( path ) parent = os . path . dirname ( absolute ) name , _ , _ = os . path . basename ( absolute ) . rpartition ( '.py' ) fobj , path , description = imp . find_module ( name , [ parent ] ) try : imp . load_module ( n...
Return a list of the tasks stored in a file
24,446
def capture ( self , * args , ** kwargs ) : import traceback try : from StringIO import StringIO except ImportError : from io import StringIO stdout , stderr = sys . stdout , sys . stderr sys . stdout = out = StringIO ( ) sys . stderr = err = StringIO ( ) result = { 'exception' : None , 'stderr' : None , 'stdout' : Non...
Run a task and return a dictionary with stderr stdout and the return value . Also the traceback from the exception if there was one
24,447
def dry ( self , * args , ** kwargs ) : return 'Would have executed:\n%s%s' % ( self . name , Args ( self . spec ) . explain ( * args , ** kwargs ) )
Perform a dry - run of the task
24,448
def help ( self ) : result = [ '=' * 50 , self . name ] if self . doc : result . extend ( [ '=' * 30 , self . doc ] ) override = self . overrides while override : if isinstance ( override , Shovel ) : result . append ( 'Overrides module' ) else : result . append ( 'Overrides %s' % override . file ) override = override ...
Return the help string of the task
24,449
def explain ( self , * args , ** kwargs ) : args = self . get ( * args , ** kwargs ) results = [ '%s = %s' % ( name , value ) for name , value in args . required ] results . extend ( [ '%s = %s (overridden)' % ( name , value ) for name , value in args . overridden ] ) results . extend ( [ '%s = %s (default)' % ( name ,...
Return a string that describes how these args are interpreted
24,450
def get ( self , * args , ** kwargs ) : required = [ arg for arg in self . _args if arg not in kwargs ] if len ( args ) < len ( required ) : raise TypeError ( 'Missing arguments %s' % required [ len ( args ) : ] ) required = list ( zip ( required , args ) ) args = args [ len ( required ) : ] defaulted = [ ( name , defa...
Evaluate this argspec with the provided arguments
24,451
def sumnum ( * args ) : print ( '%s = %f' % ( ' + ' . join ( args ) , sum ( float ( arg ) for arg in args ) ) )
Computes the sum of the provided numbers
24,452
def attributes ( name , ** kwargs ) : print ( '%s has attributes:' % name ) for key , value in kwargs . items ( ) : print ( '\t%s => %s' % ( key , value ) )
Prints a name and all keyword attributes
24,453
def render ( self , name , value , attrs = None , multi = False , renderer = None ) : DJANGO_111_OR_UP = ( VERSION [ 0 ] == 1 and VERSION [ 1 ] >= 11 ) or ( VERSION [ 0 ] >= 2 ) if DJANGO_111_OR_UP : return super ( DynamicRawIDWidget , self ) . render ( name , value , attrs , renderer = renderer ) if attrs is None : at...
Django < = 1 . 10 variant .
24,454
def get_context ( self , name , value , attrs ) : context = super ( DynamicRawIDWidget , self ) . get_context ( name , value , attrs ) model = self . rel . model if VERSION [ 0 ] == 2 else self . rel . to related_url = reverse ( 'admin:{0}_{1}_changelist' . format ( model . _meta . app_label , model . _meta . object_na...
Django > = 1 . 11 variant .
24,455
def get_form ( self , request , rel , admin_site ) : return DynamicRawIDFilterForm ( admin_site = admin_site , rel = rel , field_name = self . field_path , data = self . used_parameters , )
Return filter form .
24,456
def queryset ( self , request , queryset ) : if self . form . is_valid ( ) : filter_params = dict ( filter ( lambda x : bool ( x [ 1 ] ) , self . form . cleaned_data . items ( ) ) ) return queryset . filter ( ** filter_params ) return queryset
Filter queryset using params from the form .
24,457
def decorator ( cls , candidate , * exp_args , ** exp_kwargs ) : def wrapper ( control ) : @ wraps ( control ) def inner ( * args , ** kwargs ) : experiment = cls ( * exp_args , ** exp_kwargs ) experiment . control ( control , args = args , kwargs = kwargs ) experiment . candidate ( candidate , args = args , kwargs = k...
Decorate a control function in order to conduct an experiment when called .
24,458
def candidate ( self , cand_func , args = None , kwargs = None , name = 'Candidate' , context = None ) : self . _candidates . append ( { 'func' : cand_func , 'args' : args or [ ] , 'kwargs' : kwargs or { } , 'name' : name , 'context' : context or { } , } )
Adds a candidate function to an experiment . Can be used multiple times for multiple candidates .
24,459
def encode ( data ) : if riemann . network . CASHADDR_PREFIX is None : raise ValueError ( 'Network {} does not support cashaddresses.' . format ( riemann . get_current_network_name ( ) ) ) data = convertbits ( data , 8 , 5 ) checksum = calculate_checksum ( riemann . network . CASHADDR_PREFIX , data ) payload = b32encod...
bytes - > str
24,460
def decode ( data ) : if riemann . network . CASHADDR_PREFIX is None : raise ValueError ( 'Network {} does not support cashaddresses.' . format ( riemann . get_current_network_name ( ) ) ) if data . find ( riemann . network . CASHADDR_PREFIX ) != 0 : raise ValueError ( 'Malformed cashaddr. Cannot locate prefix: {}' . f...
str - > bytes
24,461
def copy ( self , outpoint = None , stack_script = None , redeem_script = None , sequence = None ) : return TxIn ( outpoint = outpoint if outpoint is not None else self . outpoint , stack_script = ( stack_script if stack_script is not None else self . stack_script ) , redeem_script = ( redeem_script if redeem_script is...
TxIn - > TxIn
24,462
def from_bytes ( TxIn , byte_string ) : outpoint = Outpoint . from_bytes ( byte_string [ : 36 ] ) script_sig_len = VarInt . from_bytes ( byte_string [ 36 : 45 ] ) script_start = 36 + len ( script_sig_len ) script_end = script_start + script_sig_len . number script_sig = byte_string [ script_start : script_end ] sequenc...
byte_string - > TxIn parses a TxIn from a byte - like object
24,463
def no_witness ( self ) : tx = bytes ( ) tx += self . version tx += VarInt ( len ( self . tx_ins ) ) . to_bytes ( ) for tx_in in self . tx_ins : tx += tx_in . to_bytes ( ) tx += VarInt ( len ( self . tx_outs ) ) . to_bytes ( ) for tx_out in self . tx_outs : tx += tx_out . to_bytes ( ) tx += self . lock_time return byte...
Tx - > bytes
24,464
def _hash_sequence ( self , sighash_type , anyone_can_pay ) : if anyone_can_pay or sighash_type == shared . SIGHASH_SINGLE : return b'\x00' * 32 else : sequences = ByteData ( ) for tx_in in self . tx_ins : sequences += tx_in . sequence return utils . hash256 ( sequences . to_bytes ( ) )
BIP143 hashSequence implementation
24,465
def _adjusted_script_code ( self , script ) : script_code = ByteData ( ) if script [ 0 ] == len ( script ) - 1 : return script script_code += VarInt ( len ( script ) ) script_code += script return script_code
Checks if the script code pased in to the sighash function is already length - prepended This will break if there s a redeem script that s just a pushdata That won t happen in practice
24,466
def _hash_outputs ( self , index , sighash_type ) : if sighash_type == shared . SIGHASH_ALL : outputs = ByteData ( ) for tx_out in self . tx_outs : outputs += tx_out . to_bytes ( ) return utils . hash256 ( outputs . to_bytes ( ) ) elif ( sighash_type == shared . SIGHASH_SINGLE and index < len ( self . tx_outs ) ) : ret...
BIP143 hashOutputs implementation
24,467
def deserialize ( serialized_script ) : deserialized = [ ] i = 0 while i < len ( serialized_script ) : current_byte = serialized_script [ i ] if current_byte == 0xab : raise NotImplementedError ( 'OP_CODESEPARATOR is a bad idea.' ) if current_byte <= 75 and current_byte != 0 : deserialized . append ( serialized_script ...
bytearray - > str
24,468
def _hsig_input ( self , index ) : hsig_input = z . ZcashByteData ( ) hsig_input += self . tx_joinsplits [ index ] . random_seed hsig_input += self . tx_joinsplits [ index ] . nullifiers hsig_input += self . joinsplit_pubkey return hsig_input . to_bytes ( )
inputs for the hsig hash
24,469
def _primary_input ( self , index ) : primary_input = z . ZcashByteData ( ) primary_input += self . tx_joinsplits [ index ] . anchor primary_input += self . tx_joinsplits [ index ] . nullifiers primary_input += self . tx_joinsplits [ index ] . commitments primary_input += self . tx_joinsplits [ index ] . vpub_old prima...
Primary input for the zkproof
24,470
def from_bytes ( SproutTx , byte_string ) : version = byte_string [ 0 : 4 ] tx_ins = [ ] tx_ins_num = shared . VarInt . from_bytes ( byte_string [ 4 : ] ) current = 4 + len ( tx_ins_num ) for _ in range ( tx_ins_num . number ) : tx_in = TxIn . from_bytes ( byte_string [ current : ] ) current += len ( tx_in ) tx_ins . a...
byte - like - > SproutTx
24,471
def copy ( self , version = None , tx_ins = None , tx_outs = None , lock_time = None , tx_joinsplits = None , joinsplit_pubkey = None , joinsplit_sig = None ) : return SproutTx ( version = version if version is not None else self . version , tx_ins = tx_ins if tx_ins is not None else self . tx_ins , tx_outs = tx_outs i...
SproutTx ... - > Tx
24,472
def _make_immutable ( self ) : self . _bytes = bytes ( self . _bytes ) self . __immutable = True
Prevents any future changes to the object
24,473
def find ( self , substring ) : if isinstance ( substring , ByteData ) : substring = substring . to_bytes ( ) return self . _bytes . find ( substring )
byte - like - > int Finds the index of substring
24,474
def from_bytes ( VarInt , byte_string ) : num = byte_string if num [ 0 ] <= 0xfc : num = num [ 0 : 1 ] non_compact = False elif num [ 0 ] == 0xfd : num = num [ 1 : 3 ] non_compact = ( num [ - 1 : ] == b'\x00' ) elif num [ 0 ] == 0xfe : num = num [ 1 : 5 ] non_compact = ( num [ - 2 : ] == b'\x00\x00' ) elif num [ 0 ] ==...
byte - like - > VarInt accepts arbitrary length input gets a VarInt off the front
24,475
def copy ( self , tx_ins = None , tx_outs = None , lock_time = None , expiry_height = None , value_balance = None , tx_shielded_spends = None , tx_shielded_outputs = None , tx_joinsplits = None , joinsplit_pubkey = None , joinsplit_sig = None , binding_sig = None ) : return SaplingTx ( tx_ins = tx_ins if tx_ins is not ...
SaplingTx ... - > SaplingTx
24,476
def encode ( data , checksum = True ) : if checksum : data = data + utils . hash256 ( data ) [ : 4 ] v , prefix = to_long ( 256 , lambda x : x , iter ( data ) ) data = from_long ( v , prefix , BASE58_BASE , lambda v : BASE58_ALPHABET [ v ] ) return data . decode ( "utf8" )
Convert binary to base58 using BASE58_ALPHABET .
24,477
def make_pkh_output_script ( pubkey , witness = False ) : if witness and not riemann . network . SEGWIT : raise ValueError ( 'Network {} does not support witness scripts.' . format ( riemann . get_current_network_name ( ) ) ) output_script = bytearray ( ) if type ( pubkey ) is not bytearray and type ( pubkey ) is not b...
bytearray - > bytearray
24,478
def _make_output ( value , output_script , version = None ) : if 'decred' in riemann . get_current_network_name ( ) : return tx . DecredTxOut ( value = value , version = version , output_script = output_script ) return tx . TxOut ( value = value , output_script = output_script )
byte - like byte - like - > TxOut
24,479
def make_sh_output ( value , output_script , witness = False ) : return _make_output ( value = utils . i2le_padded ( value , 8 ) , output_script = make_sh_output_script ( output_script , witness ) )
int str - > TxOut
24,480
def make_pkh_output ( value , pubkey , witness = False ) : return _make_output ( value = utils . i2le_padded ( value , 8 ) , output_script = make_pkh_output_script ( pubkey , witness ) )
int bytearray - > TxOut
24,481
def make_outpoint ( tx_id_le , index , tree = None ) : if 'decred' in riemann . get_current_network_name ( ) : return tx . DecredOutpoint ( tx_id = tx_id_le , index = utils . i2le_padded ( index , 4 ) , tree = utils . i2le_padded ( tree , 1 ) ) return tx . Outpoint ( tx_id = tx_id_le , index = utils . i2le_padded ( ind...
byte - like int int - > Outpoint
24,482
def make_script_sig ( stack_script , redeem_script ) : stack_script += ' {}' . format ( serialization . hex_serialize ( redeem_script ) ) return serialization . serialize ( stack_script )
str str - > bytearray
24,483
def make_legacy_input ( outpoint , stack_script , redeem_script , sequence ) : if 'decred' in riemann . get_current_network_name ( ) : return tx . DecredTxIn ( outpoint = outpoint , sequence = utils . i2le_padded ( sequence , 4 ) ) return tx . TxIn ( outpoint = outpoint , stack_script = stack_script , redeem_script = r...
Outpoint byte - like byte - like int - > TxIn
24,484
def make_witness_input ( outpoint , sequence ) : if 'decred' in riemann . get_current_network_name ( ) : return tx . DecredTxIn ( outpoint = outpoint , sequence = utils . i2le_padded ( sequence , 4 ) ) return tx . TxIn ( outpoint = outpoint , stack_script = b'' , redeem_script = b'' , sequence = utils . i2le_padded ( s...
Outpoint int - > TxIn
24,485
def length_prepend ( byte_string ) : length = tx . VarInt ( len ( byte_string ) ) return length . to_bytes ( ) + byte_string
bytes - > bytes
24,486
def _hash_to_sh_address ( script_hash , witness = False , cashaddr = True ) : addr_bytes = bytearray ( ) if riemann . network . CASHADDR_P2SH is not None and cashaddr : addr_bytes . extend ( riemann . network . CASHADDR_P2SH ) addr_bytes . extend ( script_hash ) return riemann . network . CASHADDR_ENCODER . encode ( ad...
bytes bool bool - > str cashaddrs are preferred where possible but cashaddr is ignored in most cases is there a better way to structure this?
24,487
def _ser_script_to_sh_address ( script_bytes , witness = False , cashaddr = True ) : if witness : script_hash = utils . sha256 ( script_bytes ) else : script_hash = utils . hash160 ( script_bytes ) return _hash_to_sh_address ( script_hash = script_hash , witness = witness , cashaddr = cashaddr )
makes an p2sh address from a serialized script
24,488
def make_sh_address ( script_string , witness = False , cashaddr = True ) : script_bytes = script_ser . serialize ( script_string ) return _ser_script_to_sh_address ( script_bytes = script_bytes , witness = witness , cashaddr = cashaddr )
str bool bool - > str
24,489
def to_output_script ( address ) : parsed = parse ( address ) parsed_hash = b'' try : if ( parsed . find ( riemann . network . P2WPKH_PREFIX ) == 0 and len ( parsed ) == 22 ) : return parsed except TypeError : pass try : if ( parsed . find ( riemann . network . P2WSH_PREFIX ) == 0 and len ( parsed ) == 34 ) : return pa...
str - > bytes There s probably a better way to do this
24,490
def parse_hash ( address ) : raw = parse ( address ) try : if address . find ( riemann . network . CASHADDR_PREFIX ) == 0 : if raw . find ( riemann . network . CASHADDR_P2SH ) == 0 : return raw [ len ( riemann . network . CASHADDR_P2SH ) : ] if raw . find ( riemann . network . CASHADDR_P2PKH ) == 0 : return raw [ len (...
str - > bytes There s probably a better way to do this .
24,491
def guess_version ( redeem_script ) : n = riemann . get_current_network_name ( ) if 'sprout' in n : return 1 if 'overwinter' in n : return 3 if 'sapling' in n : return 4 try : script_array = redeem_script . split ( ) script_array . index ( 'OP_CHECKSEQUENCEVERIFY' ) return 2 except ValueError : return 1
str - > int Bitcoin uses tx version 2 for nSequence signaling . Zcash uses tx version 2 for joinsplits .
24,492
def guess_sequence ( redeem_script ) : try : script_array = redeem_script . split ( ) loc = script_array . index ( 'OP_CHECKSEQUENCEVERIFY' ) return int ( script_array [ loc - 1 ] , 16 ) except ValueError : return 0xFFFFFFFE
str - > int If OP_CSV is used guess an appropriate sequence Otherwise disable RBF but leave lock_time on . Fails if there s not a constant before OP_CSV
24,493
def output ( value , address ) : script = addr . to_output_script ( address ) value = utils . i2le_padded ( value , 8 ) return tb . _make_output ( value , script )
int str - > TxOut accepts base58 or bech32 addresses
24,494
def outpoint ( tx_id , index , tree = None ) : tx_id_le = bytes . fromhex ( tx_id ) [ : : - 1 ] return tb . make_outpoint ( tx_id_le , index , tree )
hex_str int int - > Outpoint accepts block explorer txid string
24,495
def unsigned_input ( outpoint , redeem_script = None , sequence = None ) : if redeem_script is not None and sequence is None : sequence = guess_sequence ( redeem_script ) if sequence is None : sequence = 0xFFFFFFFE return tb . make_legacy_input ( outpoint = outpoint , stack_script = b'' , redeem_script = b'' , sequence...
Outpoint byte - like int - > TxIn
24,496
def p2pkh_input ( outpoint , sig , pubkey , sequence = 0xFFFFFFFE ) : stack_script = '{sig} {pk}' . format ( sig = sig , pk = pubkey ) stack_script = script_ser . serialize ( stack_script ) return tb . make_legacy_input ( outpoint , stack_script , b'' , sequence )
OutPoint hex_string hex_string int - > TxIn Create a signed legacy TxIn from a p2pkh prevout
24,497
def p2sh_input ( outpoint , stack_script , redeem_script , sequence = None ) : if sequence is None : sequence = guess_sequence ( redeem_script ) stack_script = script_ser . serialize ( stack_script ) redeem_script = script_ser . hex_serialize ( redeem_script ) redeem_script = script_ser . serialize ( redeem_script ) re...
OutPoint str str int - > TxIn Create a signed legacy TxIn from a p2pkh prevout
24,498
def copy ( self , tx_ins = None , tx_outs = None , lock_time = None , expiry_height = None , tx_joinsplits = None , joinsplit_pubkey = None , joinsplit_sig = None ) : return OverwinterTx ( tx_ins = tx_ins if tx_ins is not None else self . tx_ins , tx_outs = tx_outs if tx_outs is not None else self . tx_outs , lock_time...
OverwinterTx ... - > OverwinterTx
24,499
def from_bytes ( OverwinterTx , byte_string ) : header = byte_string [ 0 : 4 ] group_id = byte_string [ 4 : 8 ] if header != b'\x03\x00\x00\x80' or group_id != b'\x70\x82\xc4\x03' : raise ValueError ( 'Bad header or group ID. Expected {} and {}. Got: {} and {}' . format ( b'\x03\x00\x00\x80' . hex ( ) , b'\x70\x82\xc4\...
byte - like - > OverwinterTx