signature:
def construct ( cls , project , * , run = None , name = None , data = None , ** desc ) :
    """Construct an animation , set the runner , and add in the two
 " reserved fields " ` name ` and ` data ` ."""

implementation:
from . failed import Failed
exception = desc . pop ( '_exception' , None )
if exception :
    a = Failed ( project . layout , desc , exception )
else :
    try :
        a = cls ( project . layout , ** desc )
        a . _set_runner ( run or { } )
    except Exception as e :
        if cls . FAIL_ON_EXCEPTION :
            raise
        a = Failed ( project . layout , desc , e )
a . name = name
a . data = data
return a


signature:
def convert_mode ( image , mode = 'RGB' ) :
    """Return an image in the given mode ."""

implementation:
deprecated . deprecated ( 'util.gif.convert_model' )
return image if ( image . mode == mode ) else image . convert ( mode = mode )


signature:
def image_to_colorlist ( image , container = list ) :
    """Given a PIL . Image , returns a ColorList of its pixels ."""

implementation:
deprecated . deprecated ( 'util.gif.image_to_colorlist' )
return container ( convert_mode ( image ) . getdata ( ) )


signature:
def animated_gif_to_colorlists ( image , container = list ) :
    """Given an animated GIF , return a list with a colorlist for each frame ."""

implementation:
deprecated . deprecated ( 'util.gif.animated_gif_to_colorlists' )
from PIL import ImageSequence
it = ImageSequence . Iterator ( image )
return [ image_to_colorlist ( i , container ) for i in it ]


signature:
def parse ( s ) :
    """Parse a string representing a time interval or duration into seconds ,
 or raise an exception
 : param str s : a string representation of a time interval
 : raises ValueError : if ` ` s ` ` can ' t be interpreted as a duration"""

implementation:
parts = s . replace ( ',' , ' ' ) . split ( )
if not parts :
    raise ValueError ( 'Cannot parse empty string' )
pieces = [ ]
for part in parts :
    m = PART_MATCH ( part )
    pieces . extend ( m . groups ( ) if m else [ part ] )
if len ( pieces ) == 1 :
    pieces . append ( 's' )
if len ( pieces ) % 2 :
    raise ValueError ( 'Malformed duration %s: %s: %s' % ( s , parts , pieces ) )
result = 0
for number , units in zip ( * [ iter ( pieces ) ] * 2 ) :
    number = float ( number )
    if number < 0 :
        raise ValueError ( 'Durations cannot have negative components' )
    result += number * _get_units ( units )
return result


signature:
def opener ( ip_address , port , delay = 1 ) :
    """Wait a little and then open a web browser page for the control panel ."""

implementation:
global WEBPAGE_OPENED
if WEBPAGE_OPENED :
    return
WEBPAGE_OPENED = True
raw_opener ( ip_address , port , delay )


signature:
def raw_opener ( ip_address , port , delay = 1 ) :
    """Wait a little and then open a web browser page for the control panel ."""

implementation:
def target ( ) :
    time . sleep ( delay )
    url = 'http://%s:%d' % ( ip_address , port )
    webbrowser . open ( url , new = 0 , autoraise = True )
threading . Thread ( target = target , daemon = True ) . start ( )


signature:
def start ( self , threaded ) :
    """Creates and starts the project ."""

implementation:
self . stop ( )
self . __class__ . _INSTANCE = weakref . ref ( self )
self . is_running = True
if threaded :
    self . thread = runnable . LoopThread ( )
    self . thread . run_once = self . _target
    self . thread . start ( )
else :
    self . _target ( )


signature:
def stop ( self ) :
    """Stop the Runner if it ' s running .
 Called as a classmethod , stop the running instance if any ."""

implementation:
if self . is_running :
    log . info ( 'Stopping' )
    self . is_running = False
    self . __class__ . _INSTANCE = None
    try :
        self . thread and self . thread . stop ( )
    except :
        log . error ( 'Error stopping thread' )
        traceback . print_exc ( )
    self . thread = None
    return True


signature:
def show_image ( setter , width , height , image_path = '' , image_obj = None , offset = ( 0 , 0 ) , bgcolor = COLORS . Off , brightness = 255 ) :
    """Display an image on a matrix ."""

implementation:
bgcolor = color_scale ( bgcolor , brightness )
img = image_obj
if image_path and not img :
    from PIL import Image
    img = Image . open ( image_path )
elif not img :
    raise ValueError ( 'Must provide either image_path or image_obj' )
w = min ( width - offset [ 0 ] , img . size [ 0 ] )
h = min ( height - offset [ 1 ] , img . size [ 1 ] )
ox = offset [ 0 ]
oy = offset [ 1 ]
for x in range ( ox , w + ox ) :
    for y in range ( oy , h + oy ) :
        r , g , b , a = ( 0 , 0 , 0 , 255 )
        rgba = img . getpixel ( ( x - ox , y - oy ) )
        if isinstance ( rgba , int ) :
            raise ValueError ( 'Image must be in RGB or RGBA format!' )
        if len ( rgba ) == 3 :
            r , g , b = rgba
        elif len ( rgba ) == 4 :
            r , g , b , a = rgba
        else :
            raise ValueError ( 'Image must be in RGB or RGBA format!' )
        if a == 0 :
            r , g , b = bgcolor
        else :
            r , g , b = color_scale ( ( r , g , b ) , a )
        if brightness != 255 :
            r , g , b = color_scale ( ( r , g , b ) , brightness )
        setter ( x , y , ( r , g , b ) )


signature:
def showImage ( layout , imagePath = "" , imageObj = None , offset = ( 0 , 0 ) , bgcolor = COLORS . Off , brightness = 255 ) :
    """Display an image on the matrix"""

implementation:
if not isinstance ( layout , Matrix ) :
    raise RuntimeError ( "Must use Matrix with showImage!" )
layout . all_off ( )
return show_image ( layout . set , layout . width , layout . height , imagePath , imageObj , offset , bgcolor , brightness )


signature:
def loadImage ( layout , imagePath = "" , imageObj = None , offset = ( 0 , 0 ) , bgcolor = COLORS . Off , brightness = 255 ) :
    """Display an image on the matrix"""

implementation:
if not isinstance ( layout , Matrix ) :
    raise RuntimeError ( "Must use Matrix with loadImage!" )
texture = [ [ COLORS . Off for x in range ( layout . width ) ] for y in range ( layout . height ) ]
def setter ( x , y , pixel ) :
    if y >= 0 and x >= 0 :
        texture [ y ] [ x ] = pixel
show_image ( setter , layout . width , layout . height , imagePath , imageObj , offset , bgcolor , brightness )
return texture


signature:
def serpentine_x ( x , y , matrix ) :
    """Every other row is indexed in reverse ."""

implementation:
if y % 2 :
    return matrix . columns - 1 - x , y
return x , y


signature:
def serpentine_y ( x , y , matrix ) :
    """Every other column is indexed in reverse ."""

implementation:
if x % 2 :
    return x , matrix . rows - 1 - y
return x , y


signature:
def to_triplets ( colors ) :
    """Coerce a list into a list of triplets .
 If ` colors ` is a list of lists or strings , return it as is . Otherwise ,
 divide it into tuplets of length three , silently discarding any extra
 elements beyond a multiple of three ."""

implementation:
try :
    colors [ 0 ] [ 0 ]
    return colors
except :
    pass
# It ' s a 1 - dimensional list
extra = len ( colors ) % 3
if extra :
    colors = colors [ : - extra ]
return list ( zip ( * [ iter ( colors ) ] * 3 ) )


signature:
def colors_no_palette ( colors = None , ** kwds ) :
    """Return a Palette but don ' t take into account Pallete Names ."""

implementation:
if isinstance ( colors , str ) :
    colors = _split_colors ( colors )
else :
    colors = to_triplets ( colors or ( ) )
colors = ( color ( c ) for c in colors or ( ) )
return palette . Palette ( colors , ** kwds )


signature:
def flatten ( master ) :
    """: param dict master : a multilevel dictionary
 : return : a flattened dictionary
 : rtype : dict
 Flattens a multilevel dictionary into a single - level one so that : :
 { ' foo ' :
 { ' bar ' :
 ' a ' : 1,
 ' b ' : True ,
 ' c ' : ' hello ' ,
 would become : :
 { ' foo . bar . a ' : 1,
 ' foo . bar . b ' : True ,
 ' foo . bar . a ' : 1,
 You can mix and match both input ( hierarchical ) and output ( dotted ) formats
 in the input without problems - and if you call flatten more than once , it
 has no effect ."""

implementation:
result = { }
def add ( value , * keys ) :
    if keys in result :
        raise ValueError ( 'Duplicate key %s' % keys )
    result [ keys ] = value
def recurse ( value , * keys ) :
    if isinstance ( value , dict ) :
        for k , v in value . items ( ) :
            recurse ( v , k , * keys )
    else :
        key = '.' . join ( reversed ( keys ) )
        if key in result :
            raise ValueError ( 'Duplicate key %s' % str ( keys ) )
        result [ key ] = value
recurse ( master )
return result


signature:
def unflatten ( master ) :
    """: param dict master : a multilevel dictionary
 : return : a unflattened dictionary
 : rtype : dict
 Unflattens a single - level dictionary a multilevel into one so that : :
 { ' foo . bar . a ' : 1,
 ' foo . bar . b ' : True ,
 ' foo . bar . a ' : 1,
 would become : :
 { ' foo ' :
 { ' bar ' :
 ' a ' : 1,
 ' b ' : True ,
 ' c ' : ' hello ' ,"""

implementation:
result = { }
for k , v in master . items ( ) :
    * first , last = k . split ( '.' )
    r = result
    for i in first :
        r = r . setdefault ( i , { } )
    r [ last ] = v
return result


signature:
def receive ( self , msg ) :
    """Receives a message , and either sets it immediately , or puts it on the
 edit queue if there is one ."""

implementation:
if self . edit_queue :
    self . edit_queue . put_edit ( self . _set , msg )
else :
    self . _set ( msg )


signature:
def make_matrix_coord_map ( dx , dy , serpentine = True , offset = 0 , rotation = 0 , y_flip = False ) :
    """Helper method to generate X , Y coordinate maps for strips"""

implementation:
result = [ ]
for y in range ( dy ) :
    if not serpentine or y % 2 == 0 :
        result . append ( [ ( dx * y ) + x + offset for x in range ( dx ) ] )
    else :
        result . append ( [ dx * ( y + 1 ) - 1 - x + offset for x in range ( dx ) ] )
result = rotate_and_flip ( result , rotation , y_flip )
return result


signature:
def make_object ( * args , typename = None , python_path = None , datatype = None , ** kwds ) :
    """Make an object from a symbol ."""

implementation:
datatype = datatype or import_symbol ( typename , python_path )
field_types = getattr ( datatype , 'FIELD_TYPES' , fields . FIELD_TYPES )
return datatype ( * args , ** fields . component ( kwds , field_types ) )


signature:
def pid_context ( pid_filename = None ) :
    """For the duration of this context manager , put the PID for this process into
 ` pid _ filename ` , and then remove the file at the end ."""

implementation:
pid_filename = pid_filename or DEFAULT_PID_FILENAME
if os . path . exists ( pid_filename ) :
    contents = open ( pid_filename ) . read ( 16 )
    log . warning ( 'pid_filename %s already exists with contents %s' , pid_filename , contents )
with open ( pid_filename , 'w' ) as fp :
    fp . write ( str ( os . getpid ( ) ) )
    fp . write ( '\n' )
try :
    yield
finally :
    try :
        os . remove ( pid_filename )
    except Exception as e :
        log . error ( 'Got an exception %s deleting the pid_filename %s' , e , pid_filename )


signature:
def index ( self , i , length = None ) :
    """Return an integer index or None"""

implementation:
if self . begin <= i <= self . end :
    index = i - self . BEGIN - self . offset
    if length is None :
        length = self . full_range ( )
    else :
        length = min ( length , self . full_range ( ) )
    if 0 <= index < length :
        return index


signature:
def read_from ( self , data , pad = 0 ) :
    """Returns a generator with the elements " data " taken by offset , restricted
 by self . begin and self . end , and padded on either end by ` pad ` to get
 back to the original length of ` data `"""

implementation:
for i in range ( self . BEGIN , self . END + 1 ) :
    index = self . index ( i , len ( data ) )
    yield pad if index is None else data [ index ]


signature:
def _clean_animation ( desc , parent ) :
    """Cleans up all sorts of special cases that humans want when entering
 an animation from a yaml file .
 1 . Loading it from a file
 2 . Using just a typename instead of a dict
 3 . A single dict representing an animation , with a run : section .
 4 . ( Legacy ) Having a dict with parallel elements run : and animation :
 5 . ( Legacy ) A tuple or list : ( animation , run )"""

implementation:
desc = load . load_if_filename ( desc ) or desc
if isinstance ( desc , str ) :
    animation = { 'typename' : desc }
elif not isinstance ( desc , dict ) :
    raise TypeError ( 'Unexpected type %s in collection' % type ( desc ) )
elif 'typename' in desc or 'animation' not in desc :
    animation = desc
else :
    animation = desc . pop ( 'animation' , { } )
    if isinstance ( animation , str ) :
        animation = { 'typename' : animation }
    animation [ 'run' ] = desc . pop ( 'run' , { } )
    if desc :
        raise ValueError ( 'Extra animation fields: ' + ', ' . join ( desc ) )
animation . setdefault ( 'typename' , DEFAULT_ANIMATION )
animation = construct . to_type_constructor ( animation , ANIMATION_PATH )
datatype = animation . setdefault ( 'datatype' , failed . Failed )
animation . setdefault ( 'name' , datatype . __name__ )
# Children without fps or sleep _ time get it from their parents .
# TODO : We shouldn ' t have to rewrite our descriptions here ! The
# animation engine should be smart enough to figure out the right
# speed to run a subanimation without a run : section .
run = animation . setdefault ( 'run' , { } )
run_parent = parent . setdefault ( 'run' , { } )
if not ( 'fps' in run or 'sleep_time' in run ) :
    if 'fps' in run_parent :
        run . update ( fps = run_parent [ 'fps' ] )
    elif 'sleep_time' in run_parent :
        run . update ( sleep_time = run_parent [ 'sleep_time' ] )
return animation


signature:
def _make_names_unique ( animations ) :
    """Given a list of animations , some of which might have duplicate names , rename
 the first one to be < duplicate > _ 0 , the second < duplicate > _ 1,
 < duplicate > _ 2 , etc ."""

implementation:
counts = { }
for a in animations :
    c = counts . get ( a [ 'name' ] , 0 ) + 1
    counts [ a [ 'name' ] ] = c
    if c > 1 :
        a [ 'name' ] += '_' + str ( c - 1 )
dupes = set ( k for k , v in counts . items ( ) if v > 1 )
for a in animations :
    if a [ 'name' ] in dupes :
        a [ 'name' ] += '_0'


signature:
def detach ( self , overlay ) :
    """Give each animation a unique , mutable layout so they can run
 independently ."""

implementation:
# See # 868
for i , a in enumerate ( self . animations ) :
    a . layout = a . layout . clone ( )
    if overlay and i :
        a . preclear = False


signature:
def main ( ) :
    """If a project has a Curses driver , the section " main " in the section
 " run " must be " bibliopixel . drivers . curses . Curses . main " ."""

implementation:
if not _curses : # https : / / stackoverflow . com / a / 1325587/43839
    if os . name == 'nt' :
        raise ValueError ( 'curses is not supported under Windows' )
    raise ValueError ( 'Your platform does not support curses.' )
try :
    driver = next ( iter ( Curses . DRIVERS ) )
except :
    raise ValueError ( 'No Curses driver in project' )
_curses . wrapper ( driver . run_in_curses )


signature:
def merge ( * projects ) :
    """Merge zero or more dictionaries representing projects with the default
 project dictionary and return the result"""

implementation:
result = { }
for project in projects :
    for name , section in ( project or { } ) . items ( ) :
        if name not in PROJECT_SECTIONS :
            raise ValueError ( UNKNOWN_SECTION_ERROR % name )
        if section is None :
            result [ name ] = type ( result [ name ] ) ( )
            continue
        if name in NOT_MERGEABLE + SPECIAL_CASE :
            result [ name ] = section
            continue
        if section and not isinstance ( section , ( dict , str ) ) :
            cname = section . __class__ . __name__
            raise ValueError ( SECTION_ISNT_DICT_ERROR % ( name , cname ) )
        if name == 'animation' : # Useful hack to allow you to load projects as animations .
            adesc = load . load_if_filename ( section )
            if adesc :
                section = adesc . get ( 'animation' , { } )
                section [ 'run' ] = adesc . get ( 'run' , { } )
        result_section = result . setdefault ( name , { } )
        section = construct . to_type ( section )
        for k , v in section . items ( ) :
            if v is None :
                result_section . pop ( k , None )
            else :
                result_section [ k ] = v
return result


signature:
def copy ( self ) :
    """Copy the instance and make sure not to use a reference"""

implementation: return self . __class__ ( amount = self [ "amount" ] , asset = self [ "asset" ] . copy ( ) , blockchain_instance = self . blockchain , )


signature:
def asset ( self ) :
    """Returns the asset as instance of : class : ` . asset . Asset `"""

implementation:
if not self [ "asset" ] :
    self [ "asset" ] = self . asset_class ( self [ "symbol" ] , blockchain_instance = self . blockchain )
return self [ "asset" ]


signature:
def refresh ( self ) :
    """Refresh / Obtain an account ' s data from the API server"""

implementation:
import re
if re . match ( r"^1\.2\.[0-9]*$" , self . identifier ) :
    account = self . blockchain . rpc . get_objects ( [ self . identifier ] ) [ 0 ]
else :
    account = self . blockchain . rpc . lookup_account_names ( [ self . identifier ] ) [ 0 ]
if not account :
    raise AccountDoesNotExistsException ( self . identifier )
self . store ( account , "name" )
if self . full : # pragma : no cover
    accounts = self . blockchain . rpc . get_full_accounts ( [ account [ "id" ] ] , False )
    if accounts and isinstance ( accounts , list ) :
        account = accounts [ 0 ] [ 1 ]
    else :
        raise AccountDoesNotExistsException ( self . identifier )
    super ( Account , self ) . __init__ ( account [ "account" ] , blockchain_instance = self . blockchain )
    for k , v in account . items ( ) :
        if k != "account" :
            self [ k ] = v
else :
    super ( Account , self ) . __init__ ( account , blockchain_instance = self . blockchain )


signature:
def balances ( self ) :
    """List balances of an account . This call returns instances of
 : class : ` amount . Amount ` ."""

implementation:
balances = self . blockchain . rpc . get_account_balances ( self [ "id" ] , [ ] )
return [ self . amount_class ( b , blockchain_instance = self . blockchain ) for b in balances if int ( b [ "amount" ] ) > 0 ]


signature:
def balance ( self , symbol ) :
    """Obtain the balance of a specific Asset . This call returns instances of
 : class : ` amount . Amount ` ."""

implementation:
if isinstance ( symbol , dict ) and "symbol" in symbol :
    symbol = symbol [ "symbol" ]
balances = self . balances
for b in balances :
    if b [ "symbol" ] == symbol :
        return b
return self . amount_class ( 0 , symbol , blockchain_instance = self . blockchain )


signature:
def history ( self , first = 0 , last = 0 , limit = - 1 , only_ops = [ ] , exclude_ops = [ ] ) :
    """Returns a generator for individual account transactions . The
 latest operation will be first . This call can be used in a
 ` ` for ` ` loop .
 : param int first : sequence number of the first
 transaction to return ( * optional * )
 : param int last : sequence number of the last
 transaction to return ( * optional * )
 : param int limit : limit number of transactions to
 return ( * optional * )
 : param array only _ ops : Limit generator by these
 operations ( * optional * )
 : param array exclude _ ops : Exclude these operations from
 generator ( * optional * ) .
 . . . note : :
 only _ ops and exclude _ ops takes an array of strings :
 The full list of operation ID ' s can be found in
 operationids . py .
 Example : [ ' transfer ' , ' fill _ order ' ]"""

implementation:
_limit = 100
cnt = 0
if first < 0 :
    first = 0
while True : # RPC call
    txs = self . blockchain . rpc . get_account_history ( self [ "id" ] , "1.11.{}" . format ( last ) , _limit , "1.11.{}" . format ( first - 1 ) , api = "history" , )
    for i in txs :
        if ( exclude_ops and self . operations . getOperationNameForId ( i [ "op" ] [ 0 ] ) in exclude_ops ) :
            continue
        if ( not only_ops or self . operations . getOperationNameForId ( i [ "op" ] [ 0 ] ) in only_ops ) :
            cnt += 1
            yield i
            if limit >= 0 and cnt >= limit : # pragma : no cover
                return
    if not txs :
        log . info ( "No more history returned from API node" )
        break
    if len ( txs ) < _limit :
        log . info ( "Less than {} have been returned." . format ( _limit ) )
        break
    first = int ( txs [ - 1 ] [ "id" ] . split ( "." ) [ 2 ] )


signature:
def upgrade ( self ) : # pragma : no cover
    """Upgrade account to life time member"""

implementation:
assert callable ( self . blockchain . upgrade_account )
return self . blockchain . upgrade_account ( account = self )


signature:
def whitelist ( self , account ) : # pragma : no cover
    """Add an other account to the whitelist of this account"""

implementation:
assert callable ( self . blockchain . account_whitelist )
return self . blockchain . account_whitelist ( account , lists = [ "white" ] , account = self )


signature:
def blacklist ( self , account ) : # pragma : no cover
    """Add an other account to the blacklist of this account"""

implementation:
assert callable ( self . blockchain . account_whitelist )
return self . blockchain . account_whitelist ( account , lists = [ "black" ] , account = self )


signature:
def nolist ( self , account ) : # pragma : no cover
    """Remove an other account from any list of this account"""

implementation:
assert callable ( self . blockchain . account_whitelist )
return self . blockchain . account_whitelist ( account , lists = [ ] , account = self )


signature:
def account ( self ) :
    """In oder to obtain the actual
 : class : ` account . Account ` from this class , you can
 use the ` ` account ` ` attribute ."""

implementation:
account = self . account_class ( self [ "owner" ] , blockchain_instance = self . blockchain )
# account . refresh ( )
return account


signature:
def recover_public_key ( digest , signature , i , message = None ) :
    """Recover the public key from the the signature"""

implementation:
# See http : / / www . secg . org / download / aid - 780 / sec1 - v2 . pdf section 4.1.6 primarily
curve = ecdsa . SECP256k1 . curve
G = ecdsa . SECP256k1 . generator
order = ecdsa . SECP256k1 . order
yp = i % 2
r , s = ecdsa . util . sigdecode_string ( signature , order )
# 1.1
x = r + ( i // 2 ) * order
# 1.3 . This actually calculates for either effectively 02 | | X or 03 | | X depending on ' k ' instead of always for 02 | | X as specified .
# This substitutes for the lack of reversing R later on . - R actually is defined to be just flipping the y - coordinate in the elliptic curve .
alpha = ( ( x * x * x ) + ( curve . a ( ) * x ) + curve . b ( ) ) % curve . p ( )
beta = ecdsa . numbertheory . square_root_mod_prime ( alpha , curve . p ( ) )
y = beta if ( beta - yp ) % 2 == 0 else curve . p ( ) - beta
# 1.4 Constructor of Point is supposed to check if nR is at infinity .
R = ecdsa . ellipticcurve . Point ( curve , x , y , order )
# 1.5 Compute e
e = ecdsa . util . string_to_number ( digest )
# 1.6 Compute Q = r ^ - 1 ( sR - eG )
Q = ecdsa . numbertheory . inverse_mod ( r , order ) * ( s * R + ( - e % order ) * G )
if SECP256K1_MODULE == "cryptography" and message is not None :
    if not isinstance ( message , bytes ) :
        message = bytes ( message , "utf-8" )
        # pragma : no cover
    sigder = encode_dss_signature ( r , s )
    public_key = ec . EllipticCurvePublicNumbers ( Q . _Point__x , Q . _Point__y , ec . SECP256K1 ( ) ) . public_key ( default_backend ( ) )
    public_key . verify ( sigder , message , ec . ECDSA ( hashes . SHA256 ( ) ) )
    return public_key
else : # Not strictly necessary , but let ' s verify the message for paranoia ' s sake .
    if not ecdsa . VerifyingKey . from_public_point ( Q , curve = ecdsa . SECP256k1 ) . verify_digest ( signature , digest , sigdecode = ecdsa . util . sigdecode_string ) : # pragma : no cover
        return None
        # pragma : no cover
    return ecdsa . VerifyingKey . from_public_point ( Q , curve = ecdsa . SECP256k1 )


signature:
def recoverPubkeyParameter ( message , digest , signature , pubkey ) :
    """Use to derive a number that allows to easily recover the
 public key from the signature"""

implementation:
if not isinstance ( message , bytes ) :
    message = bytes ( message , "utf-8" )
    # pragma : no cover
for i in range ( 0 , 4 ) :
    if SECP256K1_MODULE == "secp256k1" : # pragma : no cover
        sig = pubkey . ecdsa_recoverable_deserialize ( signature , i )
        p = secp256k1 . PublicKey ( pubkey . ecdsa_recover ( message , sig ) )
        if p . serialize ( ) == pubkey . serialize ( ) :
            return i
    elif SECP256K1_MODULE == "cryptography" and not isinstance ( pubkey , PublicKey ) :
        p = recover_public_key ( digest , signature , i , message )
        p_comp = hexlify ( compressedPubkey ( p ) )
        pubkey_comp = hexlify ( compressedPubkey ( pubkey ) )
        if p_comp == pubkey_comp :
            return i
    else : # pragma : no cover
        p = recover_public_key ( digest , signature , i )
        p_comp = hexlify ( compressedPubkey ( p ) )
        p_string = hexlify ( p . to_string ( ) )
        if isinstance ( pubkey , PublicKey ) : # pragma : no cover
            pubkey_string = bytes ( repr ( pubkey ) , "ascii" )
        else : # pragma : no cover
            pubkey_string = hexlify ( pubkey . to_string ( ) )
        if p_string == pubkey_string or p_comp == pubkey_string : # pragma : no cover
            return i


signature:
def sign_message ( message , wif , hashfn = hashlib . sha256 ) :
    """Sign a digest with a wif key
 : param str wif : Private key in"""

implementation:
if not isinstance ( message , bytes ) :
    message = bytes ( message , "utf-8" )
digest = hashfn ( message ) . digest ( )
priv_key = PrivateKey ( wif )
p = bytes ( priv_key )
if SECP256K1_MODULE == "secp256k1" :
    ndata = secp256k1 . ffi . new ( "const int *ndata" )
    ndata [ 0 ] = 0
    while True :
        ndata [ 0 ] += 1
        privkey = secp256k1 . PrivateKey ( p , raw = True )
        sig = secp256k1 . ffi . new ( "secp256k1_ecdsa_recoverable_signature *" )
        signed = secp256k1 . lib . secp256k1_ecdsa_sign_recoverable ( privkey . ctx , sig , digest , privkey . private_key , secp256k1 . ffi . NULL , ndata )
        if not signed == 1 : # pragma : no cover
            raise AssertionError ( )
        signature , i = privkey . ecdsa_recoverable_serialize ( sig )
        if _is_canonical ( signature ) :
            i += 4
            # compressed
            i += 27
            # compact
            break
elif SECP256K1_MODULE == "cryptography" :
    cnt = 0
    private_key = ec . derive_private_key ( int ( repr ( priv_key ) , 16 ) , ec . SECP256K1 ( ) , default_backend ( ) )
    public_key = private_key . public_key ( )
    while True :
        cnt += 1
        if not cnt % 20 : # pragma : no cover
            log . info ( "Still searching for a canonical signature. Tried %d times already!" % cnt )
        order = ecdsa . SECP256k1 . order
        # signer = private _ key . signer ( ec . ECDSA ( hashes . SHA256 ( ) ) )
        # signer . update ( message )
        # sigder = signer . finalize ( )
        sigder = private_key . sign ( message , ec . ECDSA ( hashes . SHA256 ( ) ) )
        r , s = decode_dss_signature ( sigder )
        signature = ecdsa . util . sigencode_string ( r , s , order )
        # Make sure signature is canonical !
        sigder = bytearray ( sigder )
        lenR = sigder [ 3 ]
        lenS = sigder [ 5 + lenR ]
        if lenR is 32 and lenS is 32 : # Derive the recovery parameter
            i = recoverPubkeyParameter ( message , digest , signature , public_key )
            i += 4
            # compressed
            i += 27
            # compact
            break
else : # pragma : no branch # pragma : no cover
    cnt = 0
    sk = ecdsa . SigningKey . from_string ( p , curve = ecdsa . SECP256k1 )
    while 1 :
        cnt += 1
        if not cnt % 20 : # pragma : no branch
            log . info ( "Still searching for a canonical signature. Tried %d times already!" % cnt )
        # Deterministic k
        k = ecdsa . rfc6979 . generate_k ( sk . curve . generator . order ( ) , sk . privkey . secret_multiplier , hashlib . sha256 , hashlib . sha256 ( digest + struct . pack ( "d" , time . time ( ) ) # use the local time to randomize the signature
        ) . digest ( ) , )
        # Sign message
        sigder = sk . sign_digest ( digest , sigencode = ecdsa . util . sigencode_der , k = k )
        # Reformating of signature
        r , s = ecdsa . util . sigdecode_der ( sigder , sk . curve . generator . order ( ) )
        signature = ecdsa . util . sigencode_string ( r , s , sk . curve . generator . order ( ) )
        # Make sure signature is canonical !
        sigder = bytearray ( sigder )
        lenR = sigder [ 3 ]
        lenS = sigder [ 5 + lenR ]
        if lenR is 32 and lenS is 32 : # Derive the recovery parameter
            i = recoverPubkeyParameter ( message , digest , signature , sk . get_verifying_key ( ) )
            i += 4
            # compressed
            i += 27
            # compact
            break
# pack signature
sigstr = struct . pack ( "<B" , i )
sigstr += signature
return sigstr


signature:
def getBlockParams ( ws ) :
    """Auxiliary method to obtain ` ` ref _ block _ num ` ` and
 ` ` ref _ block _ prefix ` ` . Requires a websocket connection to a
 witness node !"""

implementation:
dynBCParams = ws . get_dynamic_global_properties ( )
ref_block_num = dynBCParams [ "head_block_number" ] & 0xFFFF
ref_block_prefix = struct . unpack_from ( "<I" , unhexlify ( dynBCParams [ "head_block_id" ] ) , 4 ) [ 0 ]
return ref_block_num , ref_block_prefix


signature:
def formatTimeFromNow ( secs = 0 ) :
    """Properly Format Time that is ` x ` seconds in the future
 : param int secs : Seconds to go in the future ( ` x > 0 ` ) or the past ( ` x < 0 ` )
 : return : Properly formated time for Graphene ( ` % Y - % m - % dT % H : % M : % S ` )
 : rtype : str"""

implementation: return datetime . utcfromtimestamp ( time . time ( ) + int ( secs ) ) . strftime ( timeformat )


signature:
def block_time ( self , block_num ) :
    """Returns a datetime of the block with the given block
 number .
 : param int block _ num : Block number"""

implementation: return self . block_class ( block_num , blockchain_instance = self . blockchain ) . time ( )


signature:
def block_timestamp ( self , block_num ) :
    """Returns the timestamp of the block with the given block
 number .
 : param int block _ num : Block number"""

implementation: return int ( self . block_class ( block_num , blockchain_instance = self . blockchain ) . time ( ) . timestamp ( ) )


signature:
def blocks ( self , start = None , stop = None ) :
    """Yields blocks starting from ` ` start ` ` .
 : param int start : Starting block
 : param int stop : Stop at this block
 : param str mode : We here have the choice between
 " head " ( the last block ) and " irreversible " ( the block that is
 confirmed by 2/3 of all block producers and is thus irreversible )"""

implementation:
# Let ' s find out how often blocks are generated !
self . block_interval = self . get_block_interval ( )
if not start :
    start = self . get_current_block_num ( )
# We are going to loop indefinitely
while True : # Get chain properies to identify the
    if stop :
        head_block = stop
    else :
        head_block = self . get_current_block_num ( )
    # Blocks from start until head block
    for blocknum in range ( start , head_block + 1 ) : # Get full block
        block = self . wait_for_and_get_block ( blocknum )
        block . update ( { "block_num" : blocknum } )
        yield block
    # Set new start
    start = head_block + 1
    if stop and start > stop : # raise StopIteration
        return
    # Sleep for one block
    time . sleep ( self . block_interval )


signature:
def wait_for_and_get_block ( self , block_number , blocks_waiting_for = None ) :
    """Get the desired block from the chain , if the current head block is
 smaller ( for both head and irreversible ) then we wait , but a
 maxmimum of blocks _ waiting _ for * max _ block _ wait _ repetition time
 before failure .
 : param int block _ number : desired block number
 : param int blocks _ waiting _ for : ( default ) difference between
 block _ number and current head how many blocks we are willing to
 wait , positive int"""

implementation:
if not blocks_waiting_for :
    blocks_waiting_for = max ( 1 , block_number - self . get_current_block_num ( ) )
repetition = 0
# can ' t return the block before the chain has reached it ( support
# future block _ num )
while self . get_current_block_num ( ) < block_number :
    repetition += 1
    time . sleep ( self . block_interval )
    if repetition > blocks_waiting_for * self . max_block_wait_repetition :
        raise Exception ( "Wait time for new block exceeded, aborting" )
# block has to be returned properly
block = self . blockchain . rpc . get_block ( block_number )
repetition = 0
while not block :
    repetition += 1
    time . sleep ( self . block_interval )
    if repetition > self . max_block_wait_repetition :
        raise Exception ( "Wait time for new block exceeded, aborting" )
    block = self . blockchain . rpc . get_block ( block_number )
return block


signature:
def ops ( self , start = None , stop = None , ** kwargs ) :
    """Yields all operations ( excluding virtual operations ) starting from
 ` ` start ` ` .
 : param int start : Starting block
 : param int stop : Stop at this block
 : param str mode : We here have the choice between
 " head " ( the last block ) and " irreversible " ( the block that is
 confirmed by 2/3 of all block producers and is thus irreversible )
 : param bool only _ virtual _ ops : Only yield virtual operations
 This call returns a list that only carries one operation and
 its type !"""

implementation:
for block in self . blocks ( start = start , stop = stop , ** kwargs ) :
    for tx in block [ "transactions" ] :
        for op in tx [ "operations" ] : # Replace opid by op name
            op [ 0 ] = self . operationids . getOperationName ( op [ 0 ] )
            yield { "block_num" : block [ "block_num" ] , "op" : op , "timestamp" : block [ "timestamp" ] , }


signature:
def stream ( self , opNames = [ ] , * args , ** kwargs ) :
    """Yield specific operations ( e . g . comments ) only
 : param array opNames : List of operations to filter for
 : param int start : Start at this block
 : param int stop : Stop at this block
 : param str mode : We here have the choice between
 * " head " : the last block
 * " irreversible " : the block that is confirmed by 2/3 of all
 block producers and is thus irreversible !
 The dict output is formated such that ` ` type ` ` caries the
 operation type , timestamp and block _ num are taken from the
 block the operation was stored in and the other key depend
 on the actualy operation ."""

implementation:
for op in self . ops ( ** kwargs ) :
    if not opNames or op [ "op" ] [ 0 ] in opNames :
        r = { "type" : op [ "op" ] [ 0 ] , "timestamp" : op . get ( "timestamp" ) , "block_num" : op . get ( "block_num" ) , }
        r . update ( op [ "op" ] [ 1 ] )
        yield r


signature:
def awaitTxConfirmation ( self , transaction , limit = 10 ) :
    """Returns the transaction as seen by the blockchain after being
 included into a block
 . . note : : If you want instant confirmation , you need to instantiate
 class : ` . blockchain . Blockchain ` with
 ` ` mode = " head " ` ` , otherwise , the call will wait until
 confirmed in an irreversible block .
 . . note : : This method returns once the blockchain has included a
 transaction with the * * same signature * * . Even though the
 signature is not usually used to identify a transaction ,
 it still cannot be forfeited and is derived from the
 transaction contented and thus identifies a transaction
 uniquely ."""

implementation:
counter = 10
for block in self . blocks ( ) :
    counter += 1
    for tx in block [ "transactions" ] :
        if sorted ( tx [ "signatures" ] ) == sorted ( transaction [ "signatures" ] ) :
            return tx
    if counter > limit :
        raise Exception ( "The operation has not been added after 10 blocks!" )


signature:
def get_all_accounts ( self , start = "" , stop = "" , steps = 1e3 , ** kwargs ) :
    """Yields account names between start and stop .
 : param str start : Start at this account name
 : param str stop : Stop at this account name
 : param int steps : Obtain ` ` steps ` ` ret with a single call from RPC"""

implementation:
lastname = start
while True :
    ret = self . blockchain . rpc . lookup_accounts ( lastname , steps )
    for account in ret :
        yield account [ 0 ]
        if account [ 0 ] == stop :
            raise StopIteration
    if lastname == ret [ - 1 ] [ 0 ] :
        raise StopIteration
    lastname = ret [ - 1 ] [ 0 ]
    if len ( ret ) < steps :
        raise StopIteration


signature:
def refresh ( self ) :
    """Refresh the data from the API server"""

implementation:
asset = self . blockchain . rpc . get_asset ( self . identifier )
if not asset :
    raise AssetDoesNotExistsException ( self . identifier )
super ( Asset , self ) . __init__ ( asset , blockchain_instance = self . blockchain )
if self . full :
    if "bitasset_data_id" in asset :
        self [ "bitasset_data" ] = self . blockchain . rpc . get_object ( asset [ "bitasset_data_id" ] )
    self [ "dynamic_asset_data" ] = self . blockchain . rpc . get_object ( asset [ "dynamic_asset_data_id" ] )


signature:
def update_cer ( self , cer , account = None , ** kwargs ) :
    """Update the Core Exchange Rate ( CER ) of an asset"""

implementation:
assert callable ( self . blockchain . update_cer )
return self . blockchain . update_cer ( self [ "symbol" ] , cer , account = account , ** kwargs )


signature:
def rpcexec ( self , payload ) :
    """Manual execute a command on API ( internally used )
 param str payload : The payload containing the request
 return : Servers answer to the query
 rtype : json
 raises RPCConnection : if no connction can be made
 raises UnauthorizedError : if the user is not authorized
 raise ValueError : if the API returns a non - JSON formated answer
 It is not recommended to use this method directly , unless
 you know what you are doing . All calls available to the API
 will be wrapped to methods directly : :
 info - > grapheneapi . info ( )"""

implementation:
try :
    response = requests . post ( "http://{}:{}/rpc" . format ( self . host , self . port ) , data = json . dumps ( payload , ensure_ascii = False ) . encode ( "utf8" ) , headers = self . headers , auth = ( self . username , self . password ) , )
    if response . status_code == 401 :
        raise UnauthorizedError
    ret = json . loads ( response . text )
    if "error" in ret :
        if "detail" in ret [ "error" ] :
            raise RPCError ( ret [ "error" ] [ "detail" ] )
        else :
            raise RPCError ( ret [ "error" ] [ "message" ] )
except requests . exceptions . RequestException :
    raise RPCConnection ( "Error connecting to Client!" )
except UnauthorizedError :
    raise UnauthorizedError ( "Invalid login credentials!" )
except ValueError :
    raise ValueError ( "Client returned invalid format. Expected JSON!" )
except RPCError as err :
    raise err
else :
    return ret [ "result" ]


signature:
def formatTime ( t ) :
    """Properly Format Time for permlinks"""

implementation:
if isinstance ( t , float ) :
    return datetime . utcfromtimestamp ( t ) . strftime ( timeFormat )
if isinstance ( t , datetime ) :
    return t . strftime ( timeFormat )


signature:
def formatTimeFromNow ( secs = None ) :
    """Properly Format Time that is ` x ` seconds in the future
 : param int secs : Seconds to go in the future ( ` x > 0 ` ) or the
 past ( ` x < 0 ` )
 : return : Properly formated time for Graphene ( ` % Y - % m - % dT % H : % M : % S ` )
 : rtype : str"""

implementation: return datetime . utcfromtimestamp ( time . time ( ) + int ( secs or 0 ) ) . strftime ( timeFormat )


signature:
def parse_time ( block_time ) :
    """Take a string representation of time from the blockchain , and parse it
 into datetime object ."""

implementation: return datetime . strptime ( block_time , timeFormat ) . replace ( tzinfo = timezone . utc )


signature:
def getOperationNameForId ( i : int ) :
    """Convert an operation id into the corresponding string"""

implementation:
assert isinstance ( i , ( int ) ) , "This method expects an integer argument"
for key in operations :
    if int ( operations [ key ] ) is int ( i ) :
        return key
raise ValueError ( "Unknown Operation ID %d" % i )


signature:
def unlocked ( self ) :
    """Is the store unlocked so that I can decrypt the content ?"""

implementation:
if self . password is not None :
    return bool ( self . password )
else :
    if ( "UNLOCK" in os . environ and os . environ [ "UNLOCK" ] and self . config_key in self . config and self . config [ self . config_key ] ) :
        log . debug ( "Trying to use environmental " "variable to unlock wallet" )
        self . unlock ( os . environ . get ( "UNLOCK" ) )
        return bool ( self . password )
return False


signature:
def unlock ( self , password ) :
    """The password is used to encrypt this masterpassword . To
 decrypt the keys stored in the keys database , one must use
 BIP38 , decrypt the masterpassword from the configuration
 store with the user password , and use the decrypted
 masterpassword to decrypt the BIP38 encrypted private keys
 from the keys storage !
 : param str password : Password to use for en - / de - cryption"""

implementation:
self . password = password
if self . config_key in self . config and self . config [ self . config_key ] :
    self . _decrypt_masterpassword ( )
else :
    self . _new_masterpassword ( password )
    self . _save_encrypted_masterpassword ( )


signature:
def _decrypt_masterpassword ( self ) :
    """Decrypt the encrypted masterkey"""

implementation:
aes = AESCipher ( self . password )
checksum , encrypted_master = self . config [ self . config_key ] . split ( "$" )
try :
    decrypted_master = aes . decrypt ( encrypted_master )
except Exception :
    self . _raise_wrongmasterpassexception ( )
if checksum != self . _derive_checksum ( decrypted_master ) :
    self . _raise_wrongmasterpassexception ( )
self . decrypted_master = decrypted_master


signature:
def _new_masterpassword ( self , password ) :
    """Generate a new random masterkey , encrypt it with the password and
 store it in the store .
 : param str password : Password to use for en - / de - cryption"""

implementation:
# make sure to not overwrite an existing key
if self . config_key in self . config and self . config [ self . config_key ] :
    raise Exception ( "Storage already has a masterpassword!" )
self . decrypted_master = hexlify ( os . urandom ( 32 ) ) . decode ( "ascii" )
# Encrypt and save master
self . password = password
self . _save_encrypted_masterpassword ( )
return self . masterkey


signature:
def _derive_checksum ( self , s ) :
    """Derive the checksum
 : param str s : Random string for which to derive the checksum"""

implementation:
checksum = hashlib . sha256 ( bytes ( s , "ascii" ) ) . hexdigest ( )
return checksum [ : 4 ]


signature:
def _get_encrypted_masterpassword ( self ) :
    """Obtain the encrypted masterkey
 . . note : : The encrypted masterkey is checksummed , so that we can
 figure out that a provided password is correct or not . The
 checksum is only 4 bytes long !"""

implementation:
if not self . unlocked ( ) :
    raise WalletLocked
aes = AESCipher ( self . password )
return "{}${}" . format ( self . _derive_checksum ( self . masterkey ) , aes . encrypt ( self . masterkey ) )


signature:
def change_password ( self , newpassword ) :
    """Change the password that allows to decrypt the master key"""

implementation:
if not self . unlocked ( ) :
    raise WalletLocked
self . password = newpassword
self . _save_encrypted_masterpassword ( )


signature:
def decrypt ( self , wif ) :
    """Decrypt the content according to BIP38
 : param str wif : Encrypted key"""

implementation:
if not self . unlocked ( ) :
    raise WalletLocked
return format ( bip38 . decrypt ( wif , self . masterkey ) , "wif" )


signature:
def encrypt ( self , wif ) :
    """Encrypt the content according to BIP38
 : param str wif : Unencrypted key"""

implementation:
if not self . unlocked ( ) :
    raise WalletLocked
return format ( bip38 . encrypt ( str ( wif ) , self . masterkey ) , "encwif" )


signature:
def get_private ( self ) :
    """Derive private key from the brain key and the current sequence
 number"""

implementation:
encoded = "%s %d" % ( self . brainkey , self . sequence )
a = _bytes ( encoded )
s = hashlib . sha256 ( hashlib . sha512 ( a ) . digest ( ) ) . digest ( )
return PrivateKey ( hexlify ( s ) . decode ( "ascii" ) , prefix = self . prefix )


signature:
def get_blind_private ( self ) :
    """Derive private key from the brain key ( and no sequence number )"""

implementation:
a = _bytes ( self . brainkey )
return PrivateKey ( hashlib . sha256 ( a ) . hexdigest ( ) , prefix = self . prefix )


signature:
def suggest ( ) :
    """Suggest a new random brain key . Randomness is provided by the
 operating system using ` ` os . urandom ( ) ` ` ."""

implementation:
word_count = 16
brainkey = [ None ] * word_count
dict_lines = BrainKeyDictionary . split ( "," )
assert len ( dict_lines ) == 49744
for j in range ( 0 , word_count ) :
    num = int . from_bytes ( os . urandom ( 2 ) , byteorder = "little" )
    rndMult = num / 2 ** 16
    # returns float between 0 . . 1 ( inclusive )
    wIdx = round ( len ( dict_lines ) * rndMult )
    brainkey [ j ] = dict_lines [ wIdx ]
return " " . join ( brainkey ) . upper ( )


signature:
def from_pubkey ( cls , pubkey , compressed = True , version = 56 , prefix = None ) :
    """Load an address provided the public key .
 Version : 56 = > PTS"""

implementation:
# Ensure this is a public key
pubkey = PublicKey ( pubkey , prefix = prefix or Prefix . prefix )
if compressed :
    pubkey_plain = pubkey . compressed ( )
else :
    pubkey_plain = pubkey . uncompressed ( )
sha = hashlib . sha256 ( unhexlify ( pubkey_plain ) ) . hexdigest ( )
rep = hexlify ( ripemd160 ( sha ) ) . decode ( "ascii" )
s = ( "%.2x" % version ) + rep
result = s + hexlify ( doublesha256 ( s ) [ : 4 ] ) . decode ( "ascii" )
result = hexlify ( ripemd160 ( result ) ) . decode ( "ascii" )
return cls ( result , prefix = pubkey . prefix )


signature:
def from_pubkey ( cls , pubkey , compressed = True , version = 56 , prefix = None ) : # Ensure this is a public key
    pubkey = PublicKey ( pubkey , prefix = prefix or Prefix . prefix )
    if compressed :
        pubkey_plain = pubkey . compressed ( )
    else :
        pubkey_plain = pubkey . uncompressed ( )
    """Derive address using ` ` RIPEMD160 ( SHA512 ( x ) ) ` `"""

implementation:
addressbin = ripemd160 ( hashlib . sha512 ( unhexlify ( pubkey_plain ) ) . hexdigest ( ) )
result = Base58 ( hexlify ( addressbin ) . decode ( "ascii" ) )
return cls ( result , prefix = pubkey . prefix )


signature:
def _derive_y_from_x ( self , x , is_even ) :
    """Derive y point from x point"""

implementation:
curve = ecdsa . SECP256k1 . curve
# The curve equation over F _ p is :
# y ^ 2 = x ^ 3 + ax + b
a , b , p = curve . a ( ) , curve . b ( ) , curve . p ( )
alpha = ( pow ( x , 3 , p ) + a * x + b ) % p
beta = ecdsa . numbertheory . square_root_mod_prime ( alpha , p )
if ( beta % 2 ) == is_even :
    beta = p - beta
return beta


signature:
def point ( self ) :
    """Return the point for the public key"""

implementation:
string = unhexlify ( self . unCompressed ( ) )
return ecdsa . VerifyingKey . from_string ( string [ 1 : ] , curve = ecdsa . SECP256k1 ) . pubkey . point


signature:
def child ( self , offset256 ) :
    """Derive new public key from this key and a sha256 " offset " """

implementation:
a = bytes ( self ) + offset256
s = hashlib . sha256 ( a ) . digest ( )
return self . add ( s )


signature:
def from_privkey ( cls , privkey , prefix = None ) :
    """Derive uncompressed public key"""

implementation:
privkey = PrivateKey ( privkey , prefix = prefix or Prefix . prefix )
secret = unhexlify ( repr ( privkey ) )
order = ecdsa . SigningKey . from_string ( secret , curve = ecdsa . SECP256k1 ) . curve . generator . order ( )
p = ecdsa . SigningKey . from_string ( secret , curve = ecdsa . SECP256k1 ) . verifying_key . pubkey . point
x_str = ecdsa . util . number_to_string ( p . x ( ) , order )
# y _ str = ecdsa . util . number _ to _ string ( p . y ( ) , order )
compressed = hexlify ( chr ( 2 + ( p . y ( ) & 1 ) ) . encode ( "ascii" ) + x_str ) . decode ( "ascii" )
# uncompressed = hexlify (
# chr ( 4 ) . encode ( ' ascii ' ) + x _ str + y _ str ) . decode ( ' ascii ' )
return cls ( compressed , prefix = prefix or Prefix . prefix )


signature:
def derive_private_key ( self , sequence ) :
    """Derive new private key from this private key and an arbitrary
 sequence number"""

implementation:
encoded = "%s %d" % ( str ( self ) , sequence )
a = bytes ( encoded , "ascii" )
s = hashlib . sha256 ( hashlib . sha512 ( a ) . digest ( ) ) . digest ( )
return PrivateKey ( hexlify ( s ) . decode ( "ascii" ) , prefix = self . pubkey . prefix )


signature:
def child ( self , offset256 ) :
    """Derive new private key from this key and a sha256 " offset " """

implementation:
a = bytes ( self . pubkey ) + offset256
s = hashlib . sha256 ( a ) . digest ( )
return self . derive_from_seed ( s )


signature:
def derive_from_seed ( self , offset ) :
    """Derive private key using " generate _ from _ seed " method .
 Here , the key itself serves as a ` seed ` , and ` offset `
 is expected to be a sha256 digest ."""

implementation:
seed = int ( hexlify ( bytes ( self ) ) . decode ( "ascii" ) , 16 )
z = int ( hexlify ( offset ) . decode ( "ascii" ) , 16 )
order = ecdsa . SECP256k1 . order
secexp = ( seed + z ) % order
secret = "%0x" % secexp
if len ( secret ) < 64 : # left - pad with zeroes
    secret = ( "0" * ( 64 - len ( secret ) ) ) + secret
return PrivateKey ( secret , prefix = self . pubkey . prefix )


signature:
def from_pubkey ( cls , pubkey , compressed = False , version = 56 , prefix = None ) : # Ensure this is a public key
    pubkey = PublicKey ( pubkey )
    if compressed :
        pubkey = pubkey . compressed ( )
    else :
        pubkey = pubkey . uncompressed ( )
    """Derive address using ` ` RIPEMD160 ( SHA256 ( x ) ) ` `"""

implementation:
addressbin = ripemd160 ( hexlify ( hashlib . sha256 ( unhexlify ( pubkey ) ) . digest ( ) ) )
return cls ( hexlify ( addressbin ) . decode ( "ascii" ) )


signature:
def rpcexec ( self , payload ) :
    """Execute a call by sending the payload
 : param json payload : Payload data
 : raises ValueError : if the server does not respond in proper JSON
 format
 : raises HttpInvalidStatusCode : if the server returns a status code
 that is not 200"""

implementation:
log . debug ( json . dumps ( payload ) )
query = requests . post ( self . url , json = payload , proxies = self . proxies ( ) )
if query . status_code != 200 : # pragma : no cover
    raise HttpInvalidStatusCode ( "Status code returned: {}" . format ( query . status_code ) )
return query . text


signature:
def varint ( n ) :
    """Varint encoding"""

implementation:
data = b""
while n >= 0x80 :
    data += bytes ( [ ( n & 0x7F ) | 0x80 ] )
    n >>= 7
data += bytes ( [ n ] )
return data


signature:
def varintdecode ( data ) : # pragma : no cover
    """Varint decoding"""

implementation:
shift = 0
result = 0
for b in bytes ( data ) :
    result |= ( b & 0x7F ) << shift
    if not ( b & 0x80 ) :
        break
    shift += 7
return result


signature:
def claim ( self , account = None , ** kwargs ) :
    """Claim a balance from the genesis block
 : param str balance _ id : The identifier that identifies the balance
 to claim ( 1.15 . x )
 : param str account : ( optional ) the account that owns the bet
 ( defaults to ` ` default _ account ` ` )"""

implementation:
if not account :
    if "default_account" in self . blockchain . config :
        account = self . blockchain . config [ "default_account" ]
if not account :
    raise ValueError ( "You need to provide an account" )
account = self . account_class ( account , blockchain_instance = self . blockchain )
pubkeys = self . blockchain . wallet . getPublicKeys ( )
addresses = dict ( )
for p in pubkeys :
    if p [ : len ( self . blockchain . prefix ) ] != self . blockchain . prefix :
        continue
    pubkey = self . publickey_class ( p , prefix = self . blockchain . prefix )
    addresses [ str ( self . address_class . from_pubkey ( pubkey , compressed = False , version = 0 , prefix = self . blockchain . prefix , ) ) ] = pubkey
    addresses [ str ( self . address_class . from_pubkey ( pubkey , compressed = True , version = 0 , prefix = self . blockchain . prefix , ) ) ] = pubkey
    addresses [ str ( self . address_class . from_pubkey ( pubkey , compressed = False , version = 56 , prefix = self . blockchain . prefix , ) ) ] = pubkey
    addresses [ str ( self . address_class . from_pubkey ( pubkey , compressed = True , version = 56 , prefix = self . blockchain . prefix , ) ) ] = pubkey
if self [ "owner" ] not in addresses . keys ( ) :
    raise MissingKeyError ( "Need key for address {}" . format ( self [ "owner" ] ) )
op = self . operations . Balance_claim ( ** { "fee" : { "amount" : 0 , "asset_id" : "1.3.0" } , "deposit_to_account" : account [ "id" ] , "balance_to_claim" : self [ "id" ] , "balance_owner_key" : addresses [ self [ "owner" ] ] , "total_claimed" : self [ "balance" ] , "prefix" : self . blockchain . prefix , } )
signers = [ account [ "name" ] , # The fee payer and receiver account
addresses . get ( self [ "owner" ] ) , # The genesis balance !
]
return self . blockchain . finalizeOp ( op , signers , "active" , ** kwargs )


signature:
def get_default_key_store ( * args , config , ** kwargs ) :
    """This method returns the default * * key * * store
 that uses an SQLite database internally .
 : params str appname : The appname that is used internally to distinguish
 different SQLite files"""

implementation:
kwargs [ "appname" ] = kwargs . get ( "appname" , "graphene" )
return SqliteEncryptedKeyStore ( config = config , ** kwargs )


signature:
def getOperationNameForId ( self , i ) :
    """Convert an operation id into the corresponding string"""

implementation:
for key in self . ops :
    if int ( self . ops [ key ] ) is int ( i ) :
        return key
raise ValueError ( "Unknown Operation ID %d" % i )


signature:
def shared_blockchain_instance ( self ) :
    """This method will initialize ` ` SharedInstance . instance ` ` and return it .
 The purpose of this method is to have offer single default
 instance that can be reused by multiple classes ."""

implementation:
if not self . _sharedInstance . instance :
    klass = self . get_instance_class ( )
    self . _sharedInstance . instance = klass ( ** self . _sharedInstance . config )
return self . _sharedInstance . instance


signature:
def set_shared_config ( cls , config ) :
    """This allows to set a config that will be used when calling
 ` ` shared _ blockchain _ instance ` ` and allows to define the configuration
 without requiring to actually create an instance"""

implementation:
assert isinstance ( config , dict )
cls . _sharedInstance . config . update ( config )
# if one is already set , delete
if cls . _sharedInstance . instance :
    cls . _sharedInstance . instance = None


signature:
def find_next ( self ) :
    """Find the next url in the list"""

implementation:
if int ( self . num_retries ) < 0 : # pragma : no cover
    self . _cnt_retries += 1
    sleeptime = ( self . _cnt_retries - 1 ) * 2 if self . _cnt_retries < 10 else 10
    if sleeptime :
        log . warning ( "Lost connection to node during rpcexec(): %s (%d/%d) " % ( self . url , self . _cnt_retries , self . num_retries ) + "Retrying in %d seconds" % sleeptime )
        sleep ( sleeptime )
    return next ( self . urls )
urls = [ k for k , v in self . _url_counter . items ( ) if ( # Only provide URLS if num _ retries is bigger equal 0,
# i . e . we want to do reconnects at all
int ( self . num_retries ) >= 0 # the counter for this host / endpoint should be smaller than
# num _ retries
and v <= self . num_retries # let ' s not retry with the same URL * if * we have others
# available
and ( k != self . url or len ( self . _url_counter ) == 1 ) ) ]
if not len ( urls ) :
    raise NumRetriesReached
url = urls [ 0 ]
return url


signature:
def reset_counter ( self ) :
    """reset the failed connection counters"""

implementation:
self . _cnt_retries = 0
for i in self . _url_counter :
    self . _url_counter [ i ] = 0


signature:
def refresh ( self ) :
    """Even though blocks never change , you freshly obtain its contents
 from an API with this method"""

implementation:
block = self . blockchain . rpc . get_block ( self . identifier )
if not block :
    raise BlockDoesNotExistsException
super ( Block , self ) . __init__ ( block , blockchain_instance = self . blockchain , use_cache = self . _use_cache )


implementation:
block = self . blockchain . rpc . get_block_header ( self . identifier )
if not block :
    raise BlockDoesNotExistsException
super ( BlockHeader , self ) . __init__ ( block , blockchain_instance = self . blockchain , use_cache = self . _use_cache )


signature:
def _haveKey ( self , key ) :
    """Is the key ` key ` available ?"""

implementation:
query = ( "SELECT {} FROM {} WHERE {}=?" . format ( self . __value__ , self . __tablename__ , self . __key__ ) , ( key , ) , )
connection = sqlite3 . connect ( self . sqlite_file )
cursor = connection . cursor ( )
cursor . execute ( * query )
return True if cursor . fetchone ( ) else False


signature:
def items ( self ) :
    """returns all items off the store as tuples"""

implementation:
query = "SELECT {}, {} from {}" . format ( self . __key__ , self . __value__ , self . __tablename__ )
connection = sqlite3 . connect ( self . sqlite_file )
cursor = connection . cursor ( )
cursor . execute ( query )
r = [ ]
for key , value in cursor . fetchall ( ) :
    r . append ( ( key , value ) )
return r


signature:
def get ( self , key , default = None ) :
    """Return the key if exists or a default value
 : param str value : Value
 : param str default : Default value if key not present"""

implementation:
if key in self :
    return self . __getitem__ ( key )
else :
    return default


signature:
def delete ( self , key ) :
    """Delete a key from the store
 : param str value : Value"""

implementation:
query = ( "DELETE FROM {} WHERE {}=?" . format ( self . __tablename__ , self . __key__ ) , ( key , ) , )
connection = sqlite3 . connect ( self . sqlite_file )
cursor = connection . cursor ( )
cursor . execute ( * query )
connection . commit ( )


signature:
def wipe ( self ) :
    """Wipe the store"""

implementation:
query = "DELETE FROM {}" . format ( self . __tablename__ )
connection = sqlite3 . connect ( self . sqlite_file )
cursor = connection . cursor ( )
cursor . execute ( query )
connection . commit ( )


signature:
def exists ( self ) :
    """Check if the database table exists"""

implementation:
query = ( "SELECT name FROM sqlite_master " + "WHERE type='table' AND name=?" , ( self . __tablename__ , ) , )
connection = sqlite3 . connect ( self . sqlite_file )
cursor = connection . cursor ( )
cursor . execute ( * query )
return True if cursor . fetchone ( ) else False


signature:
def create ( self ) : # pragma : no cover
    """Create the new table in the SQLite database"""

implementation:
query = ( """
            CREATE TABLE {} (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                {} STRING(256),
                {} STRING(256)
            )""" ) . format ( self . __tablename__ , self . __key__ , self . __value__ )
connection = sqlite3 . connect ( self . sqlite_file )
cursor = connection . cursor ( )
cursor . execute ( query )
connection . commit ( )


signature:
def appendOps ( self , ops , append_to = None ) :
    """Append op ( s ) to the transaction builder
 : param list ops : One or a list of operations"""

implementation:
if isinstance ( ops , list ) :
    self . ops . extend ( ops )
else :
    self . ops . append ( ops )
parent = self . parent
if parent :
    parent . _set_require_reconstruction ( )


signature:
def get_raw ( self ) :
    """Returns an instance of base " Operations " for further processing"""

implementation:
if not self . ops :
    return
ops = [ self . operations . Op_wrapper ( op = o ) for o in list ( self . ops ) ]
proposer = self . account_class ( self . proposer , blockchain_instance = self . blockchain )
data = { "fee" : { "amount" : 0 , "asset_id" : "1.3.0" } , "fee_paying_account" : proposer [ "id" ] , "expiration_time" : formatTimeFromNow ( self . proposal_expiration ) , "proposed_ops" : [ o . json ( ) for o in ops ] , "extensions" : [ ] , }
if self . proposal_review :
    data . update ( { "review_period_seconds" : self . proposal_review } )
ops = self . operations . Proposal_create ( ** data )
return self . operation_class ( ops )


signature:
def json ( self ) :
    """Show the transaction as plain json"""

implementation:
if not self . _is_constructed ( ) or self . _is_require_reconstruction ( ) :
    self . constructTx ( )
return dict ( self )


signature:
def appendSigner ( self , accounts , permission ) :
    """Try to obtain the wif key from the wallet by telling which account
 and permission is supposed to sign the transaction"""

implementation:
assert permission in self . permission_types , "Invalid permission"
if self . blockchain . wallet . locked ( ) :
    raise WalletLocked ( )
if not isinstance ( accounts , ( list , tuple , set ) ) :
    accounts = [ accounts ]
for account in accounts : # Now let ' s actually deal with the accounts
    if account not in self . signing_accounts : # is the account an instance of public key ?
        if isinstance ( account , self . publickey_class ) :
            self . appendWif ( self . blockchain . wallet . getPrivateKeyForPublicKey ( str ( account ) ) )
        # . . . or should we rather obtain the keys from an account name
        else :
            accountObj = self . account_class ( account , blockchain_instance = self . blockchain )
            required_treshold = accountObj [ permission ] [ "weight_threshold" ]
            keys = self . _fetchkeys ( accountObj , permission , required_treshold = required_treshold )
            # If we couldn ' t find an active key , let ' s try overwrite it
            # with an owner key
            if not keys and permission != "owner" :
                keys . extend ( self . _fetchkeys ( accountObj , "owner" , required_treshold = required_treshold ) )
            for x in keys :
                self . appendWif ( x [ 0 ] )
        self . signing_accounts . append ( account )


signature:
def appendWif ( self , wif ) :
    """Add a wif that should be used for signing of the transaction ."""

implementation:
if wif :
    try :
        self . privatekey_class ( wif )
        self . wifs . add ( wif )
    except Exception :
        raise InvalidWifError


signature:
def set_fee_asset ( self , fee_asset ) :
    """Set asset to fee"""

implementation:
if isinstance ( fee_asset , self . amount_class ) :
    self . fee_asset_id = fee_asset [ "id" ]
elif isinstance ( fee_asset , self . asset_class ) :
    self . fee_asset_id = fee_asset [ "id" ]
elif fee_asset :
    self . fee_asset_id = fee_asset
else :
    self . fee_asset_id = "1.3.0"


signature:
def add_required_fees ( self , ops , asset_id = "1.3.0" ) :
    """Auxiliary method to obtain the required fees for a set of
 operations . Requires a websocket connection to a witness node !"""

implementation:
ws = self . blockchain . rpc
fees = ws . get_required_fees ( [ i . json ( ) for i in ops ] , asset_id )
for i , d in enumerate ( ops ) :
    if isinstance ( fees [ i ] , list ) : # Operation is a proposal
        ops [ i ] . op . data [ "fee" ] = Asset ( amount = fees [ i ] [ 0 ] [ "amount" ] , asset_id = fees [ i ] [ 0 ] [ "asset_id" ] )
        for j , _ in enumerate ( ops [ i ] . op . data [ "proposed_ops" ] . data ) :
            ops [ i ] . op . data [ "proposed_ops" ] . data [ j ] . data [ "op" ] . op . data [ "fee" ] = Asset ( amount = fees [ i ] [ 1 ] [ j ] [ "amount" ] , asset_id = fees [ i ] [ 1 ] [ j ] [ "asset_id" ] , )
    else : # Operation is a regular operation
        ops [ i ] . op . data [ "fee" ] = Asset ( amount = fees [ i ] [ "amount" ] , asset_id = fees [ i ] [ "asset_id" ] )
return ops


signature:
def constructTx ( self ) :
    """Construct the actual transaction and store it in the class ' s dict
 store"""

implementation:
ops = list ( )
for op in self . ops :
    if isinstance ( op , ProposalBuilder ) : # This operation is a proposal an needs to be deal with
    # differently
        proposal = op . get_raw ( )
        if proposal :
            ops . append ( proposal )
    elif isinstance ( op , self . operation_class ) :
        ops . extend ( [ op ] )
    else : # otherwise , we simply wrap ops into Operations
        ops . extend ( [ self . operation_class ( op ) ] )
# We now wrap everything into an actual transaction
ops = self . add_required_fees ( ops , asset_id = self . fee_asset_id )
expiration = formatTimeFromNow ( self . expiration or self . blockchain . expiration or 30 # defaults to 30 seconds
)
ref_block_num , ref_block_prefix = self . get_block_params ( )
self . tx = self . signed_transaction_class ( ref_block_num = ref_block_num , ref_block_prefix = ref_block_prefix , expiration = expiration , operations = ops , )
dict . update ( self , self . tx . json ( ) )
self . _unset_require_reconstruction ( )


signature:
def get_block_params ( self ) :
    """Auxiliary method to obtain ` ` ref _ block _ num ` ` and
 ` ` ref _ block _ prefix ` ` . Requires a websocket connection to a
 witness node !"""

implementation:
ws = self . blockchain . rpc
dynBCParams = ws . get_dynamic_global_properties ( )
ref_block_num = dynBCParams [ "head_block_number" ] & 0xFFFF
ref_block_prefix = struct . unpack_from ( "<I" , unhexlify ( dynBCParams [ "head_block_id" ] ) , 4 ) [ 0 ]
return ref_block_num , ref_block_prefix


signature:
def sign ( self ) :
    """Sign a provided transaction with the provided key ( s )
 : param dict tx : The transaction to be signed and returned
 : param string wifs : One or many wif keys to use for signing
 a transaction . If not present , the keys will be loaded
 from the wallet as defined in " missing _ signatures " key
 of the transactions ."""

implementation:
self . constructTx ( )
if "operations" not in self or not self [ "operations" ] :
    return
# Legacy compatibility !
# If we are doing a proposal , obtain the account from the proposer _ id
if self . blockchain . proposer :
    proposer = self . account_class ( self . blockchain . proposer , blockchain_instance = self . blockchain )
    self . wifs = set ( )
    self . signing_accounts = list ( )
    self . appendSigner ( proposer [ "id" ] , "active" )
# We need to set the default prefix , otherwise pubkeys are
# presented wrongly !
if self . blockchain . rpc :
    self . operations . default_prefix = self . blockchain . rpc . chain_params [ "prefix" ]
elif "blockchain" in self :
    self . operations . default_prefix = self [ "blockchain" ] [ "prefix" ]
try :
    signedtx = self . signed_transaction_class ( ** self . json ( ) )
except Exception :
    raise ValueError ( "Invalid TransactionBuilder Format" )
if not any ( self . wifs ) :
    raise MissingKeyError
signedtx . sign ( self . wifs , chain = self . blockchain . rpc . chain_params )
self [ "signatures" ] . extend ( signedtx . json ( ) . get ( "signatures" ) )
return signedtx


signature:
def verify_authority ( self ) :
    """Verify the authority of the signed transaction"""

implementation:
try :
    if not self . blockchain . rpc . verify_authority ( self . json ( ) ) :
        raise InsufficientAuthorityError
except Exception as e :
    raise e


signature:
def broadcast ( self ) :
    """Broadcast a transaction to the blockchain network
 : param tx tx : Signed transaction to broadcast"""

implementation:
# Sign if not signed
if not self . _is_signed ( ) :
    self . sign ( )
# Cannot broadcast an empty transaction
if "operations" not in self or not self [ "operations" ] :
    log . warning ( "No operations in transaction! Returning" )
    return
# Obtain JS
ret = self . json ( )
# Debugging mode does not broadcast
if self . blockchain . nobroadcast :
    log . warning ( "Not broadcasting anything!" )
    self . clear ( )
    return ret
# Broadcast
try :
    if self . blockchain . blocking :
        ret = self . blockchain . rpc . broadcast_transaction_synchronous ( ret , api = "network_broadcast" )
        ret . update ( ** ret . get ( "trx" , { } ) )
    else :
        self . blockchain . rpc . broadcast_transaction ( ret , api = "network_broadcast" )
except Exception as e :
    raise e
finally :
    self . clear ( )
return ret


signature:
def clear ( self ) :
    """Clear the transaction builder and start from scratch"""

implementation:
self . ops = [ ]
self . wifs = set ( )
self . signing_accounts = [ ]
# This makes sure that _ is _ constructed will return False afterwards
self [ "expiration" ] = None
dict . __init__ ( self , { } )


signature:
def addSigningInformation ( self , account , permission ) :
    """This is a private method that adds side information to a
 unsigned / partial transaction in order to simplify later
 signing ( e . g . for multisig or coldstorage )
 FIXME : Does not work with owner keys !"""

implementation:
self . constructTx ( )
self [ "blockchain" ] = self . blockchain . rpc . chain_params
if isinstance ( account , self . publickey_class ) :
    self [ "missing_signatures" ] = [ str ( account ) ]
else :
    accountObj = self . account_class ( account )
    authority = accountObj [ permission ]
    # We add a required _ authorities to be able to identify
    # how to sign later . This is an array , because we
    # may later want to allow multiple operations per tx
    self . update ( { "required_authorities" : { accountObj [ "name" ] : authority } } )
    for account_auth in authority [ "account_auths" ] :
        account_auth_account = self . account_class ( account_auth [ 0 ] )
        self [ "required_authorities" ] . update ( { account_auth [ 0 ] : account_auth_account . get ( permission ) } )
    # Try to resolve required signatures for offline signing
    self [ "missing_signatures" ] = [ x [ 0 ] for x in authority [ "key_auths" ] ]
    # Add one recursion of keys from account _ auths :
    for account_auth in authority [ "account_auths" ] :
        account_auth_account = self . account_class ( account_auth [ 0 ] )
        self [ "missing_signatures" ] . extend ( [ x [ 0 ] for x in account_auth_account [ permission ] [ "key_auths" ] ] )


signature:
def appendMissingSignatures ( self ) :
    """Store which accounts / keys are supposed to sign the transaction
 This method is used for an offline - signer !"""

implementation:
missing_signatures = self . get ( "missing_signatures" , [ ] )
for pub in missing_signatures :
    wif = self . blockchain . wallet . getPrivateKeyForPublicKey ( pub )
    if wif :
        self . appendWif ( wif )


signature:
def as_base ( self , base ) :
    """Returns the price instance so that the base asset is ` ` base ` ` .
 Note : This makes a copy of the object !"""

implementation:
if base == self [ "base" ] [ "symbol" ] :
    return self . copy ( )
elif base == self [ "quote" ] [ "symbol" ] :
    return self . copy ( ) . invert ( )
else :
    raise InvalidAssetException


signature:
def as_quote ( self , quote ) :
    """Returns the price instance so that the quote asset is ` ` quote ` ` .
 Note : This makes a copy of the object !"""

implementation:
if quote == self [ "quote" ] [ "symbol" ] :
    return self . copy ( )
elif quote == self [ "base" ] [ "symbol" ] :
    return self . copy ( ) . invert ( )
else :
    raise InvalidAssetException


signature:
def invert ( self ) :
    """Invert the price ( e . g . go from ` ` USD / BTS ` ` into ` ` BTS / USD ` ` )"""

implementation:
tmp = self [ "quote" ]
self [ "quote" ] = self [ "base" ]
self [ "base" ] = tmp
if "for_sale" in self and self [ "for_sale" ] :
    self [ "for_sale" ] = self . amount_class ( self [ "for_sale" ] [ "amount" ] * self [ "price" ] , self [ "base" ] [ "symbol" ] )
return self


signature:
def json ( self ) :
    """return {
 " base " : self [ " base " ] . json ( ) ,
 " quote " : self [ " quote " ] . json ( )"""

implementation:
quote = self [ "quote" ]
base = self [ "base" ]
frac = Fraction ( int ( quote ) / int ( base ) ) . limit_denominator ( 10 ** base [ "asset" ] [ "precision" ] )
return { "base" : { "amount" : int ( frac . denominator ) , "asset_id" : base [ "asset" ] [ "id" ] } , "quote" : { "amount" : int ( frac . numerator ) , "asset_id" : quote [ "asset" ] [ "id" ] } , }


signature:
def wipe ( self ) :
    """Wipe the store"""

implementation:
keys = list ( self . keys ( ) ) . copy ( )
for key in keys :
    self . delete ( key )


signature:
def connect ( self , node = "" , rpcuser = "" , rpcpassword = "" , ** kwargs ) :
    """Connect to blockchain network ( internal use only )"""

implementation:
if not node :
    if "node" in self . config :
        node = self . config [ "node" ]
    else :
        raise ValueError ( "A Blockchain node needs to be provided!" )
if not rpcuser and "rpcuser" in self . config :
    rpcuser = self . config [ "rpcuser" ]
if not rpcpassword and "rpcpassword" in self . config :
    rpcpassword = self . config [ "rpcpassword" ]
self . rpc = self . rpc_class ( node , rpcuser , rpcpassword , ** kwargs )


signature:
def finalizeOp ( self , ops , account , permission , ** kwargs ) :
    """This method obtains the required private keys if present in
 the wallet , finalizes the transaction , signs it and
 broadacasts it
 : param operation ops : The operation ( or list of operaions ) to
 broadcast
 : param operation account : The account that authorizes the
 operation
 : param string permission : The required permission for
 signing ( active , owner , posting )
 : param object append _ to : This allows to provide an instance of
 ProposalsBuilder ( see : func : ` new _ proposal ` ) or
 TransactionBuilder ( see : func : ` new _ tx ( ) ` ) to specify
 where to put a specific operation .
 . . . note : : ` ` append _ to ` ` is exposed to every method used in the
 this class
 . . . note : :
 If ` ` ops ` ` is a list of operation , they all need to be
 signable by the same key ! Thus , you cannot combine ops
 that require active permission with ops that require
 posting permission . Neither can you use different
 accounts for different operations !
 . . . note : : This uses ` ` txbuffer ` ` as instance of
 : class : ` transactionbuilder . TransactionBuilder ` .
 You may want to use your own txbuffer"""

implementation:
if "append_to" in kwargs and kwargs [ "append_to" ] :
    if self . proposer :
        log . warning ( "You may not use append_to and self.proposer at " "the same time. Append new_proposal(..) instead" )
    # Append to the append _ to and return
    append_to = kwargs [ "append_to" ]
    parent = append_to . get_parent ( )
    assert isinstance ( append_to , ( self . transactionbuilder_class , self . proposalbuilder_class ) )
    append_to . appendOps ( ops )
    # Add the signer to the buffer so we sign the tx properly
    if isinstance ( append_to , self . proposalbuilder_class ) :
        parent . appendSigner ( append_to . proposer , permission )
    else :
        parent . appendSigner ( account , permission )
    # This returns as we used append _ to , it does NOT broadcast , or sign
    return append_to . get_parent ( )
elif self . proposer : # Legacy proposer mode !
    proposal = self . proposal ( )
    proposal . set_proposer ( self . proposer )
    proposal . set_expiration ( self . proposal_expiration )
    proposal . set_review ( self . proposal_review )
    proposal . appendOps ( ops )
    # Go forward to see what the other options do . . .
else : # Append tot he default buffer
    self . txbuffer . appendOps ( ops )
# The API that obtains the fee only allows to specify one particular
# fee asset for all operations in that transaction even though the
# blockchain itself could allow to pay multiple operations with
# different fee assets .
if "fee_asset" in kwargs and kwargs [ "fee_asset" ] :
    self . txbuffer . set_fee_asset ( kwargs [ "fee_asset" ] )
# Add signing information , signer , sign and optionally broadcast
if self . unsigned : # In case we don ' t want to sign anything
    self . txbuffer . addSigningInformation ( account , permission )
    return self . txbuffer
elif self . bundle : # In case we want to add more ops to the tx ( bundle )
    self . txbuffer . appendSigner ( account , permission )
    return self . txbuffer . json ( )
else : # default behavior : sign + broadcast
    self . txbuffer . appendSigner ( account , permission )
    self . txbuffer . sign ( )
    return self . txbuffer . broadcast ( )


signature:
def sign ( self , tx = None , wifs = [ ] ) :
    """Sign a provided transaction witht he provided key ( s )
 : param dict tx : The transaction to be signed and returned
 : param string wifs : One or many wif keys to use for signing
 a transaction . If not present , the keys will be loaded
 from the wallet as defined in " missing _ signatures " key
 of the transactions ."""

implementation:
if tx :
    txbuffer = self . transactionbuilder_class ( tx , blockchain_instance = self )
else :
    txbuffer = self . txbuffer
txbuffer . appendWif ( wifs )
txbuffer . appendMissingSignatures ( )
txbuffer . sign ( )
return txbuffer . json ( )


signature:
def broadcast ( self , tx = None ) :
    """Broadcast a transaction to the Blockchain
 : param tx tx : Signed transaction to broadcast"""

implementation:
if tx : # If tx is provided , we broadcast the tx
    return self . transactionbuilder_class ( tx , blockchain_instance = self ) . broadcast ( )
else :
    return self . txbuffer . broadcast ( )


signature:
def proposal ( self , proposer = None , proposal_expiration = None , proposal_review = None ) :
    """Return the default proposal buffer
 . . . note : : If any parameter is set , the default proposal
 parameters will be changed !"""

implementation:
if not self . _propbuffer :
    return self . new_proposal ( self . tx ( ) , proposer , proposal_expiration , proposal_review )
if proposer :
    self . _propbuffer [ 0 ] . set_proposer ( proposer )
if proposal_expiration :
    self . _propbuffer [ 0 ] . set_expiration ( proposal_expiration )
if proposal_review :
    self . _propbuffer [ 0 ] . set_review ( proposal_review )
return self . _propbuffer [ 0 ]


signature:
def new_tx ( self , * args , ** kwargs ) :
    """Let ' s obtain a new txbuffer
 : returns int txid : id of the new txbuffer"""

implementation:
builder = self . transactionbuilder_class ( * args , blockchain_instance = self , ** kwargs )
self . _txbuffers . append ( builder )
return builder


signature:
def detail ( self , * args , ** kwargs ) :
    prefix = kwargs . pop ( "prefix" , default_prefix )
    # remove dublicates
    kwargs [ "votes" ] = list ( set ( kwargs [ "votes" ] ) )
    """This is an example how to sort votes prior to using them in the
 Object"""

implementation:
# # Sort votes
# kwargs [ " votes " ] = sorted (
# kwargs [ " votes " ] ,
# key = lambda x : float ( x . split ( " : " ) [ 1 ] ) ,
return OrderedDict ( [ ( "memo_key" , PublicKey ( kwargs [ "memo_key" ] , prefix = prefix ) ) , ( "voting_account" , ObjectId ( kwargs [ "voting_account" ] , "account" ) ) , ( "num_witness" , Uint16 ( kwargs [ "num_witness" ] ) ) , ( "num_committee" , Uint16 ( kwargs [ "num_committee" ] ) ) , ( "votes" , Array ( [ VoteId ( o ) for o in kwargs [ "votes" ] ] ) ) , ( "extensions" , Set ( [ ] ) ) , ] )


signature:
def id ( self ) :
    """The transaction id of this transaction"""

implementation:
# Store signatures temporarily since they are not part of
# transaction id
sigs = self . data [ "signatures" ]
self . data . pop ( "signatures" , None )
# Generage Hash of the seriliazed version
h = hashlib . sha256 ( bytes ( self ) ) . digest ( )
# recover signatures
self . data [ "signatures" ] = sigs
# Return properly truncated tx hash
return hexlify ( h [ : 20 ] ) . decode ( "ascii" )


signature:
def sign ( self , wifkeys , chain = None ) :
    """Sign the transaction with the provided private keys .
 : param array wifkeys : Array of wif keys
 : param str chain : identifier for the chain"""

implementation:
if not chain :
    chain = self . get_default_prefix ( )
self . deriveDigest ( chain )
# Get Unique private keys
self . privkeys = [ ]
for item in wifkeys :
    if item not in self . privkeys :
        self . privkeys . append ( item )
# Sign the message with every private key given !
sigs = [ ]
for wif in self . privkeys :
    signature = sign_message ( self . message , wif )
    sigs . append ( Signature ( signature ) )
self . data [ "signatures" ] = Array ( sigs )
return self


signature:
def store ( self , data , key = None , * args , ** kwargs ) :
    """Cache the list
 : param list data : List of objects to cache"""

implementation:
list . __init__ ( self , data )
self . _store_items ( self . _cache_key ( key ) )


signature:
def store ( self , data , key = "id" ) :
    """Cache the list
 : param list data : List of objects to cache"""

implementation:
dict . __init__ ( self , data )
self . _store_item ( key )


signature:
def objectid_valid ( i ) :
    """Test if a string looks like a regular object id of the
 form : : :
 xxxx . yyyyy . zzzz
 with those being numbers ."""

implementation:
if "." not in i :
    return False
parts = i . split ( "." )
if len ( parts ) == 3 :
    try :
        [ int ( x ) for x in parts ]
        return True
    except Exception :
        pass
    return False


signature:
def refresh ( self ) :
    """This is the refresh method that overloads the prototype in
 BlockchainObject ."""

implementation: dict . __init__ ( self , self . blockchain . rpc . get_object ( self . identifier ) , blockchain_instance = self . blockchain , )


signature:
def _encrypt_xor ( a , b , aes ) :
    """Returns encrypt ( a ^ b ) ."""

implementation:
a = unhexlify ( "%0.32x" % ( int ( ( a ) , 16 ) ^ int ( hexlify ( b ) , 16 ) ) )
return aes . encrypt ( a )


signature:
def setKeys ( self , loadkeys ) :
    """This method is strictly only for in memory keys that are
 passed to Wallet with the ` ` keys ` ` argument"""

implementation:
log . debug ( "Force setting of private keys. Not using the wallet database!" )
if isinstance ( loadkeys , dict ) :
    loadkeys = list ( loadkeys . values ( ) )
elif not isinstance ( loadkeys , ( list , set ) ) :
    loadkeys = [ loadkeys ]
for wif in loadkeys :
    pub = self . publickey_from_wif ( wif )
    self . store . add ( str ( wif ) , pub )


signature:
def unlock ( self , pwd ) :
    """Unlock the wallet database"""

implementation:
if self . store . is_encrypted ( ) :
    return self . store . unlock ( pwd )


signature:
def newWallet ( self , pwd ) :
    """Create a new wallet database"""

implementation:
if self . created ( ) :
    raise WalletExists ( "You already have created a wallet!" )
self . store . unlock ( pwd )


signature:
def addPrivateKey ( self , wif ) :
    """Add a private key to the wallet database"""

implementation:
try :
    pub = self . publickey_from_wif ( wif )
except Exception :
    raise InvalidWifError ( "Invalid Key format!" )
if str ( pub ) in self . store :
    raise KeyAlreadyInStoreException ( "Key already in the store" )
self . store . add ( str ( wif ) , str ( pub ) )


signature:
def getPrivateKeyForPublicKey ( self , pub ) :
    """Obtain the private key for a given public key
 : param str pub : Public Key"""

implementation:
if str ( pub ) not in self . store :
    raise KeyNotFound
return self . store . getPrivateKeyForPublicKey ( str ( pub ) )


signature:
def removeAccount ( self , account ) :
    """Remove all keys associated with a given account"""

implementation:
accounts = self . getAccounts ( )
for a in accounts :
    if a [ "name" ] == account :
        self . store . delete ( a [ "pubkey" ] )


signature:
def getOwnerKeyForAccount ( self , name ) :
    """Obtain owner Private Key for an account from the wallet database"""

implementation:
account = self . rpc . get_account ( name )
for authority in account [ "owner" ] [ "key_auths" ] :
    key = self . getPrivateKeyForPublicKey ( authority [ 0 ] )
    if key :
        return key
raise KeyNotFound


signature:
def getMemoKeyForAccount ( self , name ) :
    """Obtain owner Memo Key for an account from the wallet database"""

implementation:
account = self . rpc . get_account ( name )
key = self . getPrivateKeyForPublicKey ( account [ "options" ] [ "memo_key" ] )
if key :
    return key
return False


signature:
def getActiveKeyForAccount ( self , name ) :
    """Obtain owner Active Key for an account from the wallet database"""

implementation:
account = self . rpc . get_account ( name )
for authority in account [ "active" ] [ "key_auths" ] :
    try :
        return self . getPrivateKeyForPublicKey ( authority [ 0 ] )
    except Exception :
        pass
return False


signature:
def getAccountFromPrivateKey ( self , wif ) :
    """Obtain account name from private key"""

implementation:
pub = self . publickey_from_wif ( wif )
return self . getAccountFromPublicKey ( pub )


signature:
def getAccountsFromPublicKey ( self , pub ) :
    """Obtain all accounts associated with a public key"""

implementation:
names = self . rpc . get_key_references ( [ str ( pub ) ] ) [ 0 ]
for name in names :
    yield name


signature:
def getAccountFromPublicKey ( self , pub ) :
    """Obtain the first account name from public key"""

implementation:
# FIXME , this only returns the first associated key .
# If the key is used by multiple accounts , this
# will surely lead to undesired behavior
names = list ( self . getAccountsFromPublicKey ( str ( pub ) ) )
if names :
    return names [ 0 ]


signature:
def getKeyType ( self , account , pub ) :
    """Get key type"""

implementation:
for authority in [ "owner" , "active" ] :
    for key in account [ authority ] [ "key_auths" ] :
        if str ( pub ) == key [ 0 ] :
            return authority
if str ( pub ) == account [ "options" ] [ "memo_key" ] :
    return "memo"
return None


signature:
def getAccounts ( self ) :
    """Return all accounts installed in the wallet database"""

implementation:
pubkeys = self . getPublicKeys ( )
accounts = [ ]
for pubkey in pubkeys : # Filter those keys not for our network
    if pubkey [ : len ( self . prefix ) ] == self . prefix :
        accounts . extend ( self . getAccountsFromPublicKey ( pubkey ) )
return accounts


signature:
def getPublicKeys ( self , current = False ) :
    """Return all installed public keys
 : param bool current : If true , returns only keys for currently
 connected blockchain"""

implementation:
pubkeys = self . store . getPublicKeys ( )
if not current :
    return pubkeys
pubs = [ ]
for pubkey in pubkeys : # Filter those keys not for our network
    if pubkey [ : len ( self . prefix ) ] == self . prefix :
        pubs . append ( pubkey )
return pubs


signature:
def rpcexec ( self , payload ) :
    """Execute a call by sending the payload
 : param json payload : Payload data
 : raises ValueError : if the server does not respond in proper JSON
 format"""

implementation:
if not self . ws : # pragma : no cover
    self . connect ( )
log . debug ( json . dumps ( payload ) )
# Mutex / Lock
# We need to lock because we need to wait for websocket
# response but don ' t want to allow other threads to send
# requests ( that might take less time ) to disturb
self . __lock . acquire ( )
# Send over websocket
try :
    self . ws . send ( json . dumps ( payload , ensure_ascii = False ) . encode ( "utf8" ) )
    # Receive from websocket
    ret = self . ws . recv ( )
finally : # Release lock
    self . __lock . release ( )
return ret


signature:
def unlock_wallet ( self , * args , ** kwargs ) :
    """Unlock the library internal wallet"""

implementation:
self . blockchain . wallet . unlock ( * args , ** kwargs )
return self


signature:
def encrypt ( self , message ) :
    """Encrypt a memo
 : param str message : clear text memo message
 : returns : encrypted message
 : rtype : str"""

implementation:
if not message :
    return None
nonce = str ( random . getrandbits ( 64 ) )
try :
    memo_wif = self . blockchain . wallet . getPrivateKeyForPublicKey ( self . from_account [ "options" ] [ "memo_key" ] )
except KeyNotFound : # if all fails , raise exception
    raise MissingKeyError ( "Memo private key {} for {} could not be found" . format ( self . from_account [ "options" ] [ "memo_key" ] , self . from_account [ "name" ] ) )
if not memo_wif :
    raise MissingKeyError ( "Memo key for %s missing!" % self . from_account [ "name" ] )
if not hasattr ( self , "chain_prefix" ) :
    self . chain_prefix = self . blockchain . prefix
enc = memo . encode_memo ( self . privatekey_class ( memo_wif ) , self . publickey_class ( self . to_account [ "options" ] [ "memo_key" ] , prefix = self . chain_prefix ) , nonce , message , )
return { "message" : enc , "nonce" : nonce , "from" : self . from_account [ "options" ] [ "memo_key" ] , "to" : self . to_account [ "options" ] [ "memo_key" ] , }


signature:
def decrypt ( self , message ) :
    """Decrypt a message
 : param dict message : encrypted memo message
 : returns : decrypted message
 : rtype : str"""

implementation:
if not message :
    return None
# We first try to decode assuming we received the memo
try :
    memo_wif = self . blockchain . wallet . getPrivateKeyForPublicKey ( message [ "to" ] )
    pubkey = message [ "from" ]
except KeyNotFound :
    try : # if that failed , we assume that we have sent the memo
        memo_wif = self . blockchain . wallet . getPrivateKeyForPublicKey ( message [ "from" ] )
        pubkey = message [ "to" ]
    except KeyNotFound : # if all fails , raise exception
        raise MissingKeyError ( "None of the required memo keys are installed!" "Need any of {}" . format ( [ message [ "to" ] , message [ "from" ] ] ) )
if not hasattr ( self , "chain_prefix" ) :
    self . chain_prefix = self . blockchain . prefix
return memo . decode_memo ( self . privatekey_class ( memo_wif ) , self . publickey_class ( pubkey , prefix = self . chain_prefix ) , message . get ( "nonce" ) , message . get ( "message" ) , )


signature:
def get_shared_secret ( priv , pub ) :
    """Derive the share secret between ` ` priv ` ` and ` ` pub ` `
 : param ` Base58 ` priv : Private Key
 : param ` Base58 ` pub : Public Key
 : return : Shared secret
 : rtype : hex
 The shared secret is generated such that : :
 Pub ( Alice ) * Priv ( Bob ) = Pub ( Bob ) * Priv ( Alice )"""

implementation:
pub_point = pub . point ( )
priv_point = int ( repr ( priv ) , 16 )
res = pub_point * priv_point
res_hex = "%032x" % res . x ( )
# Zero padding
res_hex = "0" * ( 64 - len ( res_hex ) ) + res_hex
return res_hex


signature:
def sign ( self , account = None , ** kwargs ) :
    """Sign a message with an account ' s memo key
 : param str account : ( optional ) the account that owns the bet
 ( defaults to ` ` default _ account ` ` )
 : raises ValueError : If not account for signing is provided
 : returns : the signed message encapsulated in a known format"""

implementation:
if not account :
    if "default_account" in self . blockchain . config :
        account = self . blockchain . config [ "default_account" ]
if not account :
    raise ValueError ( "You need to provide an account" )
# Data for message
account = self . account_class ( account , blockchain_instance = self . blockchain )
info = self . blockchain . info ( )
meta = dict ( timestamp = info [ "time" ] , block = info [ "head_block_number" ] , memokey = account [ "options" ] [ "memo_key" ] , account = account [ "name" ] , )
# wif key
wif = self . blockchain . wallet . getPrivateKeyForPublicKey ( account [ "options" ] [ "memo_key" ] )
# We strip the message here so we know for sure there are no trailing
# whitespaces or returns
message = self . message . strip ( )
enc_message = self . SIGNED_MESSAGE_META . format ( ** locals ( ) )
# signature
signature = hexlify ( sign_message ( enc_message , wif ) ) . decode ( "ascii" )
self . signed_by_account = account
self . signed_by_name = account [ "name" ]
self . meta = meta
self . plain_message = message
return self . SIGNED_MESSAGE_ENCAPSULATED . format ( MESSAGE_SPLIT = self . MESSAGE_SPLIT , ** locals ( ) )


signature:
def verify ( self , ** kwargs ) :
    """Verify a message with an account ' s memo key
 : param str account : ( optional ) the account that owns the bet
 ( defaults to ` ` default _ account ` ` )
 : returns : True if the message is verified successfully
 : raises InvalidMessageSignature if the signature is not ok"""

implementation:
# Split message into its parts
parts = re . split ( "|" . join ( self . MESSAGE_SPLIT ) , self . message )
parts = [ x for x in parts if x . strip ( ) ]
assert len ( parts ) > 2 , "Incorrect number of message parts"
# Strip away all whitespaces before and after the message
message = parts [ 0 ] . strip ( )
signature = parts [ 2 ] . strip ( )
# Parse the meta data
meta = dict ( re . findall ( r"(\S+)=(.*)" , parts [ 1 ] ) )
log . info ( "Message is: {}" . format ( message ) )
log . info ( "Meta is: {}" . format ( json . dumps ( meta ) ) )
log . info ( "Signature is: {}" . format ( signature ) )
# Ensure we have all the data in meta
assert "account" in meta , "No 'account' could be found in meta data"
assert "memokey" in meta , "No 'memokey' could be found in meta data"
assert "block" in meta , "No 'block' could be found in meta data"
assert "timestamp" in meta , "No 'timestamp' could be found in meta data"
account_name = meta . get ( "account" ) . strip ( )
memo_key = meta [ "memokey" ] . strip ( )
try :
    self . publickey_class ( memo_key , prefix = self . blockchain . prefix )
except Exception :
    raise InvalidMemoKeyException ( "The memo key in the message is invalid" )
# Load account from blockchain
try :
    account = self . account_class ( account_name , blockchain_instance = self . blockchain )
except AccountDoesNotExistsException :
    raise AccountDoesNotExistsException ( "Could not find account {}. Are you connected to the right chain?" . format ( account_name ) )
# Test if memo key is the same as on the blockchain
if not account [ "options" ] [ "memo_key" ] == memo_key :
    raise WrongMemoKey ( "Memo Key of account {} on the Blockchain " . format ( account [ "name" ] ) + "differs from memo key in the message: {} != {}" . format ( account [ "options" ] [ "memo_key" ] , memo_key ) )
# Reformat message
enc_message = self . SIGNED_MESSAGE_META . format ( ** locals ( ) )
# Verify Signature
pubkey = verify_message ( enc_message , unhexlify ( signature ) )
# Verify pubky
pk = self . publickey_class ( hexlify ( pubkey ) . decode ( "ascii" ) , prefix = self . blockchain . prefix )
if format ( pk , self . blockchain . prefix ) != memo_key :
    raise InvalidMessageSignature ( "The signature doesn't match the memo key" )
self . signed_by_account = account
self . signed_by_name = account [ "name" ]
self . meta = meta
self . plain_message = message
return True


implementation:
if not account :
    if "default_account" in self . blockchain . config :
        account = self . blockchain . config [ "default_account" ]
if not account :
    raise ValueError ( "You need to provide an account" )
# Data for message
account = self . account_class ( account , blockchain_instance = self . blockchain )
# wif key
wif = self . blockchain . wallet . getPrivateKeyForPublicKey ( account [ "options" ] [ "memo_key" ] )
payload = [ "from" , account [ "name" ] , "key" , account [ "options" ] [ "memo_key" ] , "time" , str ( datetime . utcnow ( ) ) , "text" , self . message , ]
enc_message = json . dumps ( payload , separators = ( "," , ":" ) )
# signature
signature = hexlify ( sign_message ( enc_message , wif ) ) . decode ( "ascii" )
return dict ( signed = enc_message , payload = payload , signature = signature )


implementation:
if not isinstance ( self . message , dict ) :
    try :
        self . message = json . loads ( self . message )
    except Exception :
        raise ValueError ( "Message must be valid JSON" )
payload = self . message . get ( "payload" )
assert payload , "Missing payload"
payload_dict = { k [ 0 ] : k [ 1 ] for k in zip ( payload [ : : 2 ] , payload [ 1 : : 2 ] ) }
signature = self . message . get ( "signature" )
account_name = payload_dict . get ( "from" ) . strip ( )
memo_key = payload_dict . get ( "key" ) . strip ( )
assert account_name , "Missing account name 'from'"
assert memo_key , "missing 'key'"
try :
    self . publickey_class ( memo_key , prefix = self . blockchain . prefix )
except Exception :
    raise InvalidMemoKeyException ( "The memo key in the message is invalid" )
# Load account from blockchain
try :
    account = self . account_class ( account_name , blockchain_instance = self . blockchain )
except AccountDoesNotExistsException :
    raise AccountDoesNotExistsException ( "Could not find account {}. Are you connected to the right chain?" . format ( account_name ) )
# Test if memo key is the same as on the blockchain
if not account [ "options" ] [ "memo_key" ] == memo_key :
    raise WrongMemoKey ( "Memo Key of account {} on the Blockchain " . format ( account [ "name" ] ) + "differs from memo key in the message: {} != {}" . format ( account [ "options" ] [ "memo_key" ] , memo_key ) )
# Ensure payload and signed match
signed_target = json . dumps ( self . message . get ( "payload" ) , separators = ( "," , ":" ) )
signed_actual = self . message . get ( "signed" )
assert ( signed_target == signed_actual ) , "payload doesn't match signed message: \n{}\n{}" . format ( signed_target , signed_actual )
# Reformat message
enc_message = self . message . get ( "signed" )
# Verify Signature
pubkey = verify_message ( enc_message , unhexlify ( signature ) )
# Verify pubky
pk = self . publickey_class ( hexlify ( pubkey ) . decode ( "ascii" ) , prefix = self . blockchain . prefix )
if format ( pk , self . blockchain . prefix ) != memo_key :
    raise InvalidMessageSignature ( "The signature doesn't match the memo key" )
self . signed_by_account = account
self . signed_by_name = account [ "name" ]
self . plain_message = payload_dict . get ( "text" )
return True