Exemple #1
0
 def createRegistCode(self,count = 50):
     ks = []
     sendtmp = str(time.time())
     
     crcount = self.createdb.select('createcount')
     print(crcount)
     if crcount == None:
         crcount = 1
         self.createdb.inset('createcount', str(crcount))
     else:
         crcount = int(crcount) + 1
         self.createdb.inset('createcount', str(crcount))
     kfrontstr = base58.b58encode_int(crcount)
     if len(kfrontstr) == 1:
         kfrontstr = '0' + kfrontstr
     for i in range(count):
         tmpn = '0x' + hashlib.md5(sendtmp + str(i)).hexdigest()
         num = int(tmpn,16)
         bastr = base58.b58encode_int(num)
         tmpka = kfrontstr + bastr
         ks.append(tmpka)
     cdic = '{"cnum":%d}'%(crcount)
     vs = [cdic] * count
     isOK = self.createdb.insetList(ks, vs)
     jout = json.dumps(ks)
     return jout,isOK
Exemple #2
0
    def reply(self, *args):
        # type: (Message, *MsgPackable) -> None
        """Replies to the sender if you're directly connected. Tries to make
        a connection otherwise

        Args:
            *args: Each argument given is a packet you wish to send. This is
                       prefixed with base.flags.whisper, so the other end will
                       receive ``[base.flags.whisper, *args]``
        """
        self.server._logger.debug(
            'Initiating a direct reply to Message ID {}'.format(self.id))
        if self.server.routing_table.get(self.sender):
            self.server.routing_table.get(self.sender).send(
                flags.whisper, flags.whisper, *args)
        else:
            self.server._logger.debug('Requesting connection for direct reply'
                                      ' to Message ID {}'.format(self.id))
            request_hash = sha384(
                self.sender + b58encode_int(getUTC()).decode()).hexdigest()
            request_id = b58encode_int(int(request_hash, 16)).decode()
            self.server.send(request_id, self.sender, type=flags.request)
            to_send = (flags.whisper,
                       flags.whisper)  # type: Tuple[MsgPackable, ...]
            self.server.requests[request_id] = to_send + args
            self.server._logger.critical(
                "You aren't connected to the original sender. This reply is "
                "not guarunteed, but we're trying to make a connection and "
                "put the message through.")
Exemple #3
0
    def __lookup(self, method, key, handler=None):
        # type: (ChordSocket, bytes, int, ChordConnection) -> awaiting_value
        """Looks up the value at a given hash function and key. This method
        deals with just *one* of the underlying hash tables.

        Args:
            method: The hash table that you wish to check. Must be a
                        :py:class:`str` or :py:class:`bytes`-like object
            key:    The key that you wish to check. Must be a :py:class:`int`
                        or :py:class:`long`

        Returns:
            The value at said key in an :py:class:`py2p.utils.awaiting_value`
            object, which either contains or will eventually contain its result
        """
        node = self  # type: Union[ChordSocket, BaseConnection]
        method = sanitize_packet(method)
        if self.routing_table:
            node = self.find(key)
        elif self.awaiting_ids:
            node = choice(self.awaiting_ids)
        if node in (self, None):
            return awaiting_value(self.data[method].get(key, None))
        else:
            node.send(flags.whisper, flags.retrieve, method,
                      b58encode_int(key))
            ret = awaiting_value()
            if handler:
                ret.callback = handler
            self.requests[method, b58encode_int(key)] = ret
            return ret
Exemple #4
0
    def __lookup(self, method, key, handler=None):
        # type: (ChordSocket, bytes, int, ChordConnection) -> awaiting_value
        """Looks up the value at a given hash function and key. This method
        deals with just *one* of the underlying hash tables.

        Args:
            method: The hash table that you wish to check. Must be a
                        :py:class:`str` or :py:class:`bytes`-like object
            key:    The key that you wish to check. Must be a :py:class:`int`
                        or :py:class:`long`

        Returns:
            The value at said key in an :py:class:`py2p.utils.awaiting_value`
            object, which either contains or will eventually contain its result
        """
        node = self  # type: Union[ChordSocket, BaseConnection]
        method = sanitize_packet(method)
        if self.routing_table:
            node = self.find(key)
        elif self.awaiting_ids:
            node = choice(self.awaiting_ids)
        if node in (self, None):
            return awaiting_value(self.data[method].get(key, None))
        else:
            node.send(flags.whisper, flags.retrieve, method,
                      b58encode_int(key))
            ret = awaiting_value()
            if handler:
                ret.callback = handler
            self.requests[method, b58encode_int(key)] = ret
            return ret
Exemple #5
0
    def get_key(cls, nickname, f_path):
        '''
        assume there is only one pair keys
        '''
        f = open(f_path, 'rb')

        # # use bitcoin to get key
        # for l in file:
        #     l_list = l.decode('utf-8').strip('\n').split(' ')
        #     if l_list[0] == nickname:
        #         G.OWNER_NICKNAME = l_list[0]
        #         G.OWNER_PRV_KEY_HEX_STR = l_list[1]
        #         G.OWNER_PUB_KEY_HEX_STR = l_list[2]
        #         file.close()
        #         G.OWNER_PRV_KEY_INT = bitcoin.decode_privkey(G.OWNER_PRV_KEY_HEX_STR, 'hex')
        #         G.OWNER_PUB_KEY_INT_COORD = bitcoin.decode_pubkey(G.OWNER_PUB_KEY_HEX_STR, 'hex')
        #         G.OWNER_ID = base58.b58encode_int(int(G.OWNER_PUB_KEY_HEX_STR, 16)).decode('utf-8')
        #         return True

        # use starkbank/ecdsa-python to get key
        for l in f:
            l_list = l.strip().split()
            if l_list[0] == nickname.encode():
                f.close()
                G.OWN_NICKNAME = l_list[0]
                G.OWN_PRV_KEY_INT = int(l_list[1], 16)
                G.OWN_PUB_KEY_INT_X = int(l_list[2], 16)
                G.OWN_PUB_KEY_INT_Y = int(l_list[3], 16)
                G.OWN_ID = base58.b58encode_int(G.OWN_PUB_KEY_INT_X) + b'+' + \
                             base58.b58encode_int(G.OWN_PUB_KEY_INT_Y)
                return True

        f.close()
        return False
Exemple #6
0
def PrivateKey():
    new_private_key = KeyTriplet()

#STEP 1. #########  GENERATE PRIVATE KEY ############

#Generate a new 32bit random key using the OS's CSPRNG:
    private_key_bytes = os.urandom(32)
    private_key_hex = private_key_bytes.hex()
    #private_key_hex = '8B7C0FCC173893EB11B15BC0015C6CABD485DAB72E2FE52E48F406406C2871FE'

    private_key_int = int(private_key_hex,16)
    #print("Private key Bytes =", private_key_bytes)
    private_key_hex = private_key_bytes.hex()
    #print("Private key Hex",private_key_hex)

    #compressed Private key
    private_key_uncomp = '80'+private_key_hex
    sha1 = sha256(binascii.unhexlify(private_key_uncomp)).hexdigest()
    sha2 = sha256(binascii.unhexlify(sha1)).hexdigest()
    first4 = sha2[0:8]
    #print("first 4 =",first4)

    private_key_w_checksum_uncmp = private_key_uncomp+first4
    #print("private_key_temp_checksum =",private_key_w_checksum_uncmp)

    private_key_uncmp_int = int(private_key_w_checksum_uncmp,16)

    #base58check
    private_uncompressed = base58.b58encode_int(private_key_uncmp_int)
    #print("private key uncompressed:",private_uncompressed)


    #uncompressed Private key
    private_key_cmp = '80'+private_key_hex+'01'
    sha1 = sha256(binascii.unhexlify(private_key_cmp)).hexdigest()
    sha2 = sha256(binascii.unhexlify(sha1)).hexdigest()
    first4_cmp = sha2[0:8]
    #print("first 4 cmp =",first4_cmp)

    private_key_w_checksum_cmp = private_key_cmp+first4_cmp


    private_key_cmp_int = int(private_key_w_checksum_cmp,16)
    #print("private_key_cmp=",private_key_w_checksum_cmp)
    private_compressed = base58.b58encode_int(private_key_cmp_int)
    #print("private key compressed:",private_compressed)

    new_private_key.compressed = private_compressed
    new_private_key.uncompressed = private_uncompressed
    new_private_key.intkey = private_key_int
    
    return new_private_key
Exemple #7
0
def pkHash(pk):
    m = bin_sha256(pk)
    m = bin_ripemd160(m)

    k = bin_sha256('6f' + m)
    k = bin_sha256(k)

    m = '6f' + m + k[:8]
    if m[0] == '0' and m[1] == '0':
        m = '1' + base58.b58encode_int(int(m, 16))
    else:
        m = base58.b58encode_int(int(m, 16))
    return m
Exemple #8
0
    async def charge(self):
        T.LOGGER.debug('')

        # charge coin: -7
        self.coin_charge = G.COIN_CREDIT

        if not await init(self, G.CHARGE):
            return False
        if self.i_m <= self.i_m_guide:
            return self.i_ch_fetch  # TODO: only consider this case now
        T.LOGGER.debug('init success')

        c = (b' '.join(self.c_rx_list[:G.P_HASH]) + b' ' +
             base58.b58encode_int(self.coin_charge) + b' ' +
             base58.b58encode_int(self.coin_rest) + b' ' +
             base58.b58encode_int(self.i_ch_m_pre) + b' ' +
             base58.b58encode_int(self.ch_own.i_ch_next) + b' ' +
             self.hash_pre)
        sign_c = Ecc.sign(c, self.ch_own.pri_key)
        hash_c = Hash.sha(c + b' ' + sign_c)
        c_auth = c + b' ' + sign_c + b' ' + hash_c  # to TX all card

        content_ack = (
            base58.b58encode_int(self.coin_charge) + b' ' +
            base58.b58encode_int(self.coin_rest) + b' ' +
            base58.b58encode_int(self.i_ch_m_pre) + b' ' +
            base58.b58encode_int(self.ch_own.i_ch_next) + b' ' +
            self.hash_pre + b' ' + sign_c + b' ' +
            hash_c  # to do, is it need to be TX
        )
        c_ack_auth = ack_god(self.ch_own, content_ack,
                             self.c_rx_list[G.P_HASH])  # to TX part card

        T.LOGGER.debug('c_auth success')
        return c_auth
Exemple #9
0
    async def run(self):
        if self.c_list[G.P_TYPE] == G.DEMAND:
            ID_earn = self.c_list[G.P_ID_DEMAND]
            ID_pay = self.c_list[G.P_ID_DEMANDED]
            i_m_pay = self.c_list[G.P_I]  # for ch_pay
            ch_pay = Chain(ID_pay, T.FO_CH)
            # fetch demand card
            c_fetch = await ch_pay.fetch_m(ID_earn, i_m_pay)
            # c_fetch_list = c_fetch.split()
            c_ack = G.ACK + b' ' +\
                    base58.b58encode_int(int(time())) + b' ' +\
                    self.ID_ack + b' ' +\
                    self.c_list[G.P_HASH] + b' ' +\
                    c_fetch

        elif self.c_list[G.P_TYPE] == G.PAY:
            ID_pay = self.c_list[G.P_ID_PAY]
            ch_pay = Chain(ID_pay, T.FO_CH)
            # add pay card into chain and update guide
            await ch_pay.append(self.c_list)

            c_ack = G.ACK + b' ' +\
                   base58.b58encode_int(int(time())) + b' ' +\
                   self.ID_ack + b' ' +\
                   self.c_list[G.P_HASH]

        elif self.c_list[G.P_TYPE] == G.EARN:
            ID_earn = self.c_list[G.P_ID_EARN]
            ch_earn = Chain(ID_earn, T.FO_CH)
            # add earn card into chain and update guide
            await ch_earn.append(self.c_list)

            c_ack = G.ACK + b' ' +\
                   base58.b58encode_int(int(time())) + b' ' +\
                   self.ID_ack + b' ' +\
                   self.c_list[G.P_HASH]
        elif self.c_list[G.P_TYPE] == G.WATCH:
            pass
        elif self.c_list[G.P_TYPE] == G.POST:
            pass
        else:
            T.LOGGER.error(b'There should not be c_type: ' +
                           self.c_list[G.P_TYPE])
            return False

        c_ack_sign = Ecc.sign(c_ack)
        c_ack_hash = Hash.sha(c_ack + b' ' + c_ack_sign)
        c_ack_auth = c_ack + b' ' + c_ack_sign + b' ' + c_ack_hash

        return c_ack_auth
Exemple #10
0
    def __store(self, method, key, value):
        # type: (ChordSocket, bytes, int, MsgPackable) -> None
        """Updates the value at a given key. This method deals with just *one*
        of the underlying hash tables.

        Args:
            method: The hash table that you wish to check. Must be a
                        :py:class:`str` or :py:class:`bytes`-like object
            key:    The key that you wish to check. Must be a :py:class:`int`
                        or :py:class:`long`
            value:  The value you wish to put at this key. Must be a
                        :py:class:`str` or :py:class:`bytes`-like object
        """
        node = self.find(key)  # type: Union[ChordSocket, BaseConnection]
        method = sanitize_packet(method)
        if self.leeching and node is self and len(self.awaiting_ids):
            node = choice(self.awaiting_ids)
        if node in (self, None):
            if value is None:
                del self.data[method][key]
            else:
                self.data[method][key] = value
        else:
            node.send(flags.whisper, flags.store, method,
                      b58encode_int(key), value)
Exemple #11
0
def _fulfillment_to_details(fulfillment):
    """
    Encode a fulfillment as a details dictionary

    Args:
        fulfillment: Crypto-conditions Fulfillment object
    """

    if fulfillment.type_name == 'ed25519-sha-256':
        return {
            'type': 'ed25519-sha-256',
            'public_key': base58.b58encode(fulfillment.public_key),
        }

    if fulfillment.type_name == 'rsa-sha-256':
        public_key = int(binascii.hexlify(fulfillment.modulus), 16)
        return {
            'type': 'rsa-sha-256',
            'public_key': base58.b58encode_int(public_key)
        }

    if fulfillment.type_name == 'threshold-sha-256':
        subconditions = [
            _fulfillment_to_details(cond['body'])
            for cond in fulfillment.subconditions
        ]
        return {
            'type': 'threshold-sha-256',
            'threshold': fulfillment.threshold,
            'subconditions': subconditions,
        }

    raise UnsupportedTypeError(fulfillment.type_name)
Exemple #12
0
 def _get_next_param_id(self):
     """Return the next parameter ID."""
     assert self.lock.locked()
     next_param_id = self._state['next_param_id']
     self._state['next_param_id'] = next_param_id + 1
     self._schedule_dump()
     return 'p-' + base58.b58encode_int(next_param_id)
Exemple #13
0
    def __store(self, method, key, value):
        # type: (ChordSocket, bytes, int, MsgPackable) -> None
        """Updates the value at a given key. This method deals with just *one*
        of the underlying hash tables.

        Args:
            method: The hash table that you wish to check. Must be a
                        :py:class:`str` or :py:class:`bytes`-like object
            key:    The key that you wish to check. Must be a :py:class:`int`
                        or :py:class:`long`
            value:  The value you wish to put at this key. Must be a
                        :py:class:`str` or :py:class:`bytes`-like object
        """
        node = self.find(key)  # type: Union[ChordSocket, BaseConnection]
        method = sanitize_packet(method)
        if self.leeching and node is self and len(self.awaiting_ids):
            node = choice(self.awaiting_ids)
        if node in (self, None):
            if value is None:
                del self.data[method][key]
            else:
                self.data[method][key] = value
        else:
            node.send(flags.whisper, flags.store, method, b58encode_int(key),
                      value)
Exemple #14
0
async def init():
    T.LOGGER.debug('')

    ID_own = None
    # load key
    try:
        c_root_auth = None
        async with aiosqlite.connect(T.PATH_CREDIT) as db:
            await db.execute('create table if not exists \
                                table_own(name nchar({0}) primary key, \
                                        id char({1}) unique, \
                                        pri_key char({2}), \
                                        pub_key_x char({2}), \
                                        pub_key_y char({2}))'. 
                                format(G.LEN_NAME, G.LEN_ID, G.LEN_KEY))
            async with db.execute('select * from table_own where name=?', (G.NAME_GOD,)) as cursor:
                async for row in cursor:
                    ID_own = row[T.P_OWN_ID]
                    T.LOGGER.debug(b'select: ' + ID_own)
                    pri_key = base58.b58decode_int(row[T.P_OWN_PRI])
                    pub_key_x = base58.b58decode_int(row[T.P_OWN_PUB_X])
                    pub_key_y = base58.b58decode_int(row[T.P_OWN_PUB_Y])
                    ch_own = Chain(T.FO_CH, ID_own, pri_key, pub_key_x, pub_key_y)
                    
            # no record, create root card
            if ID_own is None:          
                ID_own, pri_key, pub_key_x, pub_key_y = Ecc.generate()
                T.LOGGER.debug(b'create: ' + ID_own)
                pri_key_b58 = base58.b58encode_int(pri_key)
                pub_key_x_b58 = base58.b58encode_int(pub_key_x)
                pub_key_y_b58 = base58.b58encode_int(pub_key_y)
                
                await db.execute('insert into table_own values(?,?,?,?,?)',
                                    (G.NAME_GOD, ID_own, pri_key_b58, pub_key_x_b58, pub_key_y_b58))
                await db.commit()

                ch_own = Chain(T.FO_CH, ID_own, pri_key, pub_key_x, pub_key_y)
                c_root_auth = handle.root(ch_own)

        #  own chain
        if not await ch_own.init(c_root_auth):
            return False
        return ch_own
        
    except Exception as e:
        T.LOGGER.warning(e)
        return False
Exemple #15
0
 def createSoftID(self):
     tlen = len(self.db.allKeys())
     sendtmp = str(time.time())
     strtmp = self.getRandomStr()
     tmpn = '0x' + hashlib.sha256(sendtmp + strtmp + str(tlen)).hexdigest()
     num = int(tmpn,16)
     bastr = base58.b58encode_int(num)
     return bastr
def PrivateKey(integer = True, compressed = True):

#STEP 1. #########  GENERATE PRIVATE KEY ############

#Generate a new 32bit random key using the OS's CSPRNG:
    private_key_bytes = os.urandom(32)
    private_key_hex = private_key_bytes.hex()
    #private_key_hex = '8B7C0FCC173893EB11B15BC0015C6CABD485DAB72E2FE52E48F406406C2871FE'

    private_key_int = int(private_key_hex,16)
    print("Private key Bytes =", private_key_bytes)
    private_key_hex = private_key_bytes.hex()
    print("Private key Hex",private_key_hex)

    #compressed Private key
    private_key_temp = '80'+private_key_hex
    sha1 = sha256(binascii.unhexlify(private_key_temp)).hexdigest()
    sha2 = sha256(binascii.unhexlify(sha1)).hexdigest()
    first4 = sha2[0:8]
    print("first 4 =",first4)

    private_key_w_checksum_uncmp = private_key_temp+first4
    print("private_key_temp_checksum =",private_key_w_checksum_uncmp)

    private_key_uncmp_int = int(private_key_w_checksum_uncmp,16)

    #base58check
    private_uncompressed = base58.b58encode_int(private_key_uncmp_int)
    print("private key uncompressed:",private_uncompressed)


    #uncompressed Private key
    private_key_w_checksum_cmp = private_key_temp+'01'+first4
    private_key_cmp_int = int(private_key_w_checksum_cmp,16)
    print("private_key_cmp_int=",private_key_cmp_int)
    private_compressed = base58.b58encode_int(private_key_cmp_int)
    print("private key compressed:",private_compressed)
    
    if integer == True:
        return private_key_int
    else:
        if compressed == True:
            return private_compressed
        else:
            return private_uncompressed 
Exemple #17
0
    def act_group(self, c_sign_god):
        T.LOGGER.debug('')

        init_ch(self)
        c_node = (
            b' '.join(c_sign_god) + b' ' +  # 
            base58.b58encode_int(self.coin_rest) + b' ' +  # -6
            base58.b58encode_int(self.i_ch_m_pre) + b' ' +  # -5
            base58.b58encode_int(self.i_ch) + b' ' +  # -4
            self.hash_pre  # -3
        )
        T.LOGGER.debug('')
        sign_c_node = Ecc.sign(c_node, self.ch_own.pri_key)  # -2
        hash_c_node = Hash.sha(c_node + b' ' + sign_c_node)  # -1
        c_auth_node = c_node + b' ' + sign_c_node + b' ' + hash_c_node

        T.LOGGER.debug('complete')
        return c_auth_node
Exemple #18
0
def getaddress(redeem):
    m = bin_sha256(redeem)
    m = bin_ripemd160(m)

    k = bin_sha256('6f' + m)
    k = bin_sha256(k)

    m = 'c4' + m + k[:8]
    m = base58.b58encode_int(int(m, 16))
    return m
Exemple #19
0
    async def post(self):
        T.LOGGER.debug('')

        if not await init(self, G.POST):
            return False
        if self.i_m <= self.i_m_guide:
            return self.i_ch_fetch  # TODO: only consider this case now
        T.LOGGER.debug('init success')

        c = (b' '.join(self.c_rx_list[:G.P_HASH]) + b' ' +
             base58.b58encode_int(self.coin_rest) + b' ' +
             base58.b58encode_int(self.i_ch_m_pre) + b' ' +
             base58.b58encode_int(self.ch_own.i_ch_next) + b' ' +
             self.hash_pre)
        sign_c = Ecc.sign(c, self.ch_own.pri_key)
        hash_c = Hash.sha(c + b' ' + sign_c)
        c_auth = c + b' ' + sign_c + b' ' + hash_c  # to TX all card

        return c_auth
Exemple #20
0
    async def act_god(self, hash_content):
        T.LOGGER.debug('')

        await init(self, self.ID_god)
        c = (
            G.VER + b' ' +  # 0
            base58.b58encode_int(int(time())) + b' ' +  # 1
            self.type + b' ' +  # 2
            self.ID_god + b' ' +  # 3
            self.ID_post + b' ' +  # 4                
            base58.b58encode_int(self.i_m) + b' ' +  # 5
            hash_content  # 6
        )

        sign_c = Ecc.sign(c, self.ch_own.pri_key)  # -2
        hash_c = Hash.sha(c + b' ' + sign_c)  # -1

        c_auth = c + b' ' + sign_c + b' ' + hash_c
        T.LOGGER.debug(c_auth)
        return c_auth, hash_c
Exemple #21
0
    async def redeem(self):
        T.LOGGER.debug('')

        if not await self.init():
            return False

        c = (b' '.join(self.c_rx_list[:G.P_HASH]) + b' ' +
             base58.b58encode_int(self.coin_charge) + b' ' +
             base58.b58encode_int(self.coin_rest) + b' ' +
             base58.b58encode_int(self.i_ch_m_pre) + b' ' +
             base58.b58encode_int(self.ch_own.i_ch_next) + b' ' +
             self.hash_pre)

        sign_c = Ecc.sign(c, self.ch_own.pri_key)
        hash_c = Hash.sha(c + b' ' + sign_c)
        c_auth = c + b' ' + sign_c + b' ' + hash_c

        # add pay card into chain and update guide
        await self.ch_own.append(c_auth)

        return c_auth
Exemple #22
0
    def root(self):
        T.LOGGER.debug('')

        c_root = (
            G.VER + b' ' +  # 0
            base58.b58encode_int(int(time())) + b' ' +  # 1
            self.type + b' ' +  # 2
            self.ID_god + b' ' +  # 3
            self.ID_god + b' ' +  # 4
            base58.b58encode_int(self.i_m) + b' ' +  # 5
            self.hash_content + b' ' +  # 6
            base58.b58encode_int(self.coin_rest) + b' ' +  # -6
            base58.b58encode_int(self.i_ch_m_pre) + b' ' +  # -5
            base58.b58encode_int(self.i_ch) + b' ' +  # -4
            self.hash_pre  # -3
        )
        sign_c_root = Ecc.sign(c_root, self.ch_own.pri_key)  # -2
        hash_c_root = Hash.sha(c_root + b' ' + sign_c_root)  # -1
        c_root_auth = c_root + b' ' + sign_c_root + b' ' + hash_c_root

        return c_root_auth
Exemple #23
0
async def regist(cls_App, name, hash_ID_real, row_god):
    '''
    init the root card 
    row_god is in credit_DB.free_table: name, ID, credit
    '''
    T.LOGGER.debug('')

    ID_god = row_god[T.P_FREE_ID]
    ID, pri_key, pub_key_x, pub_key_y = Ecc.generate()
    pri_key_b58 = base58.b58encode_int(pri_key)
    pub_key_x_b58 = base58.b58encode_int(pub_key_x)
    pub_key_y_b58 = base58.b58encode_int(pub_key_y)

    # create init root card to chain
    ch_own = Chain(T.FO_CH, ID, pri_key, pub_key_x, pub_key_y)
    cls_App.ch_own = ch_own

    if not await charge(cls_App, ID_god, hash_ID_real, root=1):
        return False

    # add ID to table_own. to do: check the ID conflict
    try:
        async with aiosqlite.connect(T.PATH_CREDIT) as db:
            await db.execute('create table if not exists \
                                table_own(name nchar({0}) primary key, \
                                        id char({1}) unique, \
                                        pri_key char({2}), \
                                        pub_key_x char({2}), \
                                        pub_key_y char({2}))'.format(
                G.LEN_NAME, G.LEN_ID, G.LEN_KEY))

            await db.execute(
                'insert into table_own values(?,?,?,?,?)',
                (name, ID, pri_key_b58, pub_key_x_b58, pub_key_y_b58))
            await db.commit()
    except Exception as e:
        T.LOGGER.warning(e)
        return False

    return True
Exemple #24
0
    async def init(self):
        # coin_rest: -6
        if self.ch_own.c_last[G.P_ID_PAY] == self.ID_pay:
            coin_rest = (
                base58.b58decode_int(self.ch_own.c_last[G.P_COIN_REST]) -
                base58.b58decode_int(self.ch_own.c_last[G.P_COIN_TRADE]))
        else:
            coin_rest = (
                base58.b58decode_int(self.ch_own.c_last[G.P_COIN_REST]) +
                base58.b58decode_int(self.ch_own.c_last[G.P_COIN_TRADE]))
        self.coin_rest = coin_rest

        # mutual index and previous partner chain index: 5 and -5
        row = await self.ch_own.get_guide(self.ID_earn)
        if row:
            ID_earn, i_m_pay, i_ch_pay, i_m_earn, i_ch_earn = row
            i_m_pay_next = base58.b58encode_int(
                (base58.b58decode_int(i_m_pay) + 1) % G.NUM_I_M)
            # i_m_earn_next = base58.b58encode_int((base58.b58decode_int(i_m_earn) + 1) % G.NUM_I_M)
        else:
            # create DB row when ID doesn't exist, start from 1
            await self.ch_own.set_guide(self.ID_earn)
            i_ch_pay = base58.b58encode_int(0)
            i_m_pay_next = base58.b58encode_int(1)

        self.i_ch_pay_pre = i_ch_pay
        self.i_m_pay = i_m_pay_next

        # pay chain index: -4
        if self.ch_own.i_l == G.NUM_L_BODY - 1:
            i_f = self.ch_own.i_f + 1
            i_l = 0
        else:
            i_f = self.ch_own.i_f
            i_l = self.ch_own.i_l + 1
        self.i_ch = base58.b58encode_int(i_f * G.NUM_L_BODY + i_l)

        # previous hash: -3
        self.hash_pre = self.ch_own.c_last[G.P_HASH]
Exemple #25
0
 def sha(cls, text_byte):
     '''
     there is hash func in bitcoin lib, are they the same?
     In:
         text: string type of card
     Out:
         b58
     '''
     # binascii.a2b_hex(hexdigest()) = digest()
     value = hashlib.sha256(text_byte).hexdigest()
     value_int = int(value, 16)
     value_b58 = base58.b58encode_int(value_int)
     return value_b58
Exemple #26
0
def pkh_gen(pk):
    pk_bytes = bytearray.fromhex(pk)
    pk_hash160 = hash160(pk_bytes)
    version = version_dict['testnet']['pubkeyhash']
    version_bytes = bytearray.fromhex(version[2:])
    ver_pk = version_bytes + pk_hash160
    ver_pk_hash256 = hash256(ver_pk)
    check = ver_pk_hash256[:4]
    print("check:" + check)
    ver_pk_check = version_bytes + pk_hash160 + check
    ver_pk_check_int = int.from_bytes(ver_pk_check, 'big')
    output_base58 = b58encode_int(ver_pk_check_int)
    return output_base58
Exemple #27
0
    def generate(cls):
        T.LOGGER.debug('')
        # use starkbank/ecdsa-python to generate
        pri = PrivateKey()  # default curve is secp256k1
        pri_key = pri.secret

        pub = pri.publicKey()
        pub_key_x = pub.x
        pub_key_y = pub.y

        ID_int = pub_key_x * (2**G.NUM_B_ODEV) + pub_key_y % (2**G.NUM_B_ODEV)
        ID = base58.b58encode_int(ID_int)

        return ID, pri_key, pub_key_x, pub_key_y
Exemple #28
0
    def __init__(self, ID_god, ch_own, root=None):
        self.ID_charge = ch_own.ID_own
        self.ch_own = ch_own
        self.ID_god = ID_god
        self.root = root
        self.type = G.CHARGE

        # for charge root
        if self.root:
            self.i_m = 0
            self.coin_rest = 0
            self.i_ch_m_pre = 0
            self.i_ch = 0
            self.hash_pre = base58.b58encode_int(0)
Exemple #29
0
    def __init__(
            self,  # type: Any
            addr,  # type: str
            port,  # type: int
            prot=default_protocol,  # type: Protocol
            out_addr=None,  # type: Union[None, Tuple[str, int]]
            debug_level=0  # type: int
    ):  # type: (...) -> None
        """Initializes a peer to peer socket

        Args:
            addr:        The address you wish to bind to (ie: "192.168.1.1")
            port:        The port you wish to bind to (ie: 44565)
            prot:        The protocol you wish to operate over, defined by a
                             :py:class:`py2p.base.Protocol` object
            out_addr:    Your outward facing address. Only needed if you're
                             connecting over the internet. If you use '0.0.0.0'
                             for the addr argument, this will automatically be
                             set to your LAN address.
            debug_level: The verbosity you want this socket to use when
                             printing event data

        Raises:
            socket.error: The address you wanted could not be bound, or is
            otherwise used
        """
        object.__init__(self)
        EventEmitter.__init__(self)
        self.protocol = prot
        self.debug_level = debug_level
        self.routing_table = {}  # type: Dict[bytes, BaseConnection]
        # In format {ID: handler}
        self.awaiting_ids = []  # type: List[BaseConnection]
        # Connected, but not handshook yet
        if out_addr:  # Outward facing address, if you're port forwarding
            self.out_addr = out_addr
        elif addr == '0.0.0.0':
            self.out_addr = get_lan_ip(), port
        else:
            self.out_addr = addr, port
        info = (str(self.out_addr).encode(), prot.id.encode(), user_salt)
        h = sha384(b''.join(info))
        self.id = b58encode_int(int(h.hexdigest(), 16)).encode()  # type: bytes
        self._logger = getLogger('{}.{}.{}'.format(
            self.__class__.__module__, self.__class__.__name__, self.id))
        self.__handlers = [
        ]  # type: List[Callable[[Message, BaseConnection], Union[bool, None]]]
        self.__closed = False
Exemple #30
0
    async def demand(self):
        T.LOGGER.debug('')

        await self.init()

        type_c = G.DEMAND
        c = G.VER + b' ' +\
                base58.b58encode_int(int(time())) + b' ' +\
                type_c + b' ' +\
                self.ID_earn + b' ' +\
                self.ID_pay + b' ' +\
                self.i_m_earn

        sign_c = Ecc.sign(c, self.ch_own.pri_key_own)
        hash_c = Hash.sha(c + b' ' + sign_c)
        c_auth = c + b' ' + sign_c + b' ' + hash_c
        return c_auth, hash_c
Exemple #31
0
def ack_god(ch_god, content, hash_src):
    T.LOGGER.debug('')

    type_c = G.ACK

    c = (
        G.VER + b' ' +  # 0
        base58.b58encode_int(int(time())) + b' ' +  # 1
        type_c + b' ' +  # 2
        ch_god.ID_own + b' ' +  # 3
        hash_src + b' ' +  # 4                
        content + b' '  # 5
    )

    sign_c = Ecc.sign(c, ch_god.pri_key)
    hash_c = Hash.sha(c + b' ' + sign_c)
    c_auth = c + b' ' + sign_c + b' ' + hash_c
    return c_auth
Exemple #32
0
    def update(self, c_last, i_ch_0=None):
        T.LOGGER.debug('')
        
        if i_ch_0 == None: # for non-init
            if c_last[G.P_I_CH] != base58.b58encode_int(self.i_ch_next):
                T.LOGGER.error('chain index is not corrent for last card')
                return False

            self.i_ch = self.i_ch_next
            self.i_f = self.i_f_next
            self.i_l = self.i_l_next
        

        if self.i_l == G.NUM_L_BODY -1:
            self.i_f_next = self.i_f + 1
            self.i_l_next = 0
        else:
            self.i_f_next = self.i_f
            self.i_l_next = self.i_l + 1

        self.i_ch_next = self.i_f_next * G.NUM_L_BODY + self.i_l_next

        self.c_last = c_last

        if self.c_last[G.P_TYPE] == G.CHARGE:
            self.coin_rest = (base58.b58decode_int(self.c_last[G.P_COIN_REST]) + 
                                base58.b58decode_int(self.c_last[G.P_COIN_CHRE])) 
        elif self.c_last[G.P_TYPE] == G.REDEEM:
            self.coin_rest = (base58.b58decode_int(self.c_last[G.P_COIN_REST]) - 
                                base58.b58decode_int(self.c_last[G.P_COIN_CHRE])) 
        elif self.c_last[G.P_TYPE] == G.PAY:
            self.coin_rest = (base58.b58decode_int(self.c_last[G.P_COIN_REST]) - 
                                base58.b58decode_int(self.c_last[G.P_COIN_TRADE]))
        elif self.c_last[G.P_TYPE] == G.EARN:
            self.coin_rest = (base58.b58decode_int(self.c_last[G.P_COIN_REST]) +
                                base58.b58decode_int(self.c_last[G.P_COIN_TRADE]))
        else:
            self.coin_rest = base58.b58decode_int(self.c_last[G.P_COIN_REST])
        
        T.LOGGER.debug('update success')
        return True
Exemple #33
0
    async def pay(self, coin_pay):
        T.LOGGER.debug('')

        await self.init()
        c = (
            G.VER + b' ' +  # 0
            base58.b58encode_int(int(time())) + b' ' +  # 1
            self.type + b' ' +  # 2
            self.ID_pay + b' ' +  # 3
            self.ID_earn + b' ' +  # 4
            self.i_m_pay + b' ' +  # 5
            coin_pay + b' ' +  # 6
            self.coin_rest + b' ' +  # -6
            self.i_ch_pay_pre + b' ' +  # -5
            self.i_ch + b' ' +  # -4
            self.hash_pre  # -3
        )

        sign_c = Ecc.sign(c, self.ch_own.pri_key_own)  # -2
        hash_c = Hash.sha(c + b' ' + sign_c)  # -1

        c_auth = c + b' ' + sign_c + b' ' + hash_c
        return c_auth, hash_c
Exemple #34
0
    def __delta(self, method, key, delta):
        # type: (ChordSocket, bytes, int, MsgPackable) -> None
        """Updates the value at a given key, using the supplied delta. This
        method deals with just *one* of the underlying hash tables.

        Args:
            method: The hash table that you wish to check. Must be a
                        :py:class:`str` or :py:class:`bytes`-like object
            key:    The key that you wish to check. Must be a :py:class:`int`
                        or :py:class:`long`
            delta:  The delta you wish to apply at this key.
        """
        node = self.find(key)  # type: Union[ChordSocket, BaseConnection]
        method = sanitize_packet(method)
        if self.leeching and node is self and len(self.awaiting_ids):
            node = choice(self.awaiting_ids)
        if node in (self, None):
            if key not in self.data[method]:
                self.data[method][key] = {}
            self.data[method][key].update(delta)  # type: ignore
        else:
            node.send(flags.whisper, flags.delta, method,
                      b58encode_int(key), delta)
Exemple #35
0
    async def ack(self):
        T.LOGGER.debug('')

        if not await self.init():
            return False

        ID_earn = self.c_rx_list[G.P_ID_DEMAND]
        ID_pay = self.c_rx_list[G.P_ID_DEMANDED]
        i_m_pay = self.c_rx_list[G.P_I]  # for ch_pay
        ch_pay = Chain(ID_pay, T.FO_CH)
        # fetch demand card
        c_fetch = await ch_pay.fetch_m(ID_earn, i_m_pay)
        # c_fetch_list = c_fetch.split()
        c = (G.ACK + b' ' +\
                base58.b58encode_int(int(time())) + b' ' +
                self.ID_ack + b' ' +
                self.c_rx_list[G.P_HASH] + b' ' +
                c_fetch)
        sign_c = Ecc.sign(c, self.ch_own.pri_key)
        hash_c = Hash.sha(c + b' ' + sign_c)
        c_auth = c + b' ' + sign_c + b' ' + hash_c

        return c_auth
Exemple #36
0
    def __delta(self, method, key, delta):
        # type: (ChordSocket, bytes, int, MsgPackable) -> None
        """Updates the value at a given key, using the supplied delta. This
        method deals with just *one* of the underlying hash tables.

        Args:
            method: The hash table that you wish to check. Must be a
                        :py:class:`str` or :py:class:`bytes`-like object
            key:    The key that you wish to check. Must be a :py:class:`int`
                        or :py:class:`long`
            delta:  The delta you wish to apply at this key.
        """
        node = self.find(key)  # type: Union[ChordSocket, BaseConnection]
        method = sanitize_packet(method)
        if self.leeching and node is self and len(self.awaiting_ids):
            node = choice(self.awaiting_ids)
        if node in (self, None):
            if key not in self.data[method]:
                self.data[method][key] = {}
            self.data[method][key].update(delta)  # type: ignore
        else:
            node.send(flags.whisper, flags.delta, method, b58encode_int(key),
                      delta)
Exemple #37
0
def test_simple_integers():
    for idx, char in enumerate(alphabet):
        char = bytes_from_char(char)
        assert_that(b58decode_int(char), equal_to(idx))
        assert_that(b58encode_int(idx), equal_to(char))
Exemple #38
0
 def time_58(self):
     # type: (InternalMessage) -> bytes
     """Returns this message's timestamp in base_58"""
     return b58encode_int(self.__time)
Exemple #39
0
def test_large_integer():
    number = 0x111d38e5fc9071ffcd20b4a763cc9ae4f252bb4e48fd66a835e252ada93ff480d6dd43dc62a641155a5  # noqa
    assert_that(b58decode_int(alphabet), equal_to(number))
    assert_that(b58encode_int(number), equal_to(alphabet[1:]))
Exemple #40
0
 def id(self):
     # type: (Protocol) -> str
     """The SHA-256-based ID of the Protocol"""
     h = sha256(''.join(str(x) for x in self).encode())
     h.update(protocol_version.encode())
     return b58encode_int(int(h.hexdigest(), 16))