コード例 #1
0
    def output_address(self, output_index):

        # get the script
        pk_script = self._transaction.txouts[output_index].pk_script
        # get tokens for script
        tokens = Tokenizer(pk_script)

        # matching the template(P2PKH or P2PK)
        if tokens.match_template(TEMPLATE_PAY_TO_PUBKEY_HASH):
            pubkeyhash = tokens.get_value(2).vector
            return Wallet.pubkey_to_address(pubkeyhash)

        if tokens.match_template(TEMPLATE_PAY_TO_PUBKEY):
            pubkey = tokens.get_value(0).vector
            return Wallet.pubkey_to_address(pubkey)

        return None
コード例 #2
0
    def __init__(self, walletFile='mywallet.dat'):

        self.gs = dict()
        self.gs['Block'], self.gs['Transaction'], self.gs['UnspentTxOut'], self.gs['Message'], self.gs['TxIn'], \
            self.gs['TxOut'], self.gs['Peer'], self.gs['OutPoint']= globals()['Block'], globals()['Transaction'], \
            globals()['UnspentTxOut'],globals()['Message'], globals()['TxIn'], globals()['TxOut'], globals()['Peer'], \
                                                                    globals()['OutPoint']

        self.chain_lock = threading.RLock()

        self.wallet = Wallet.init_wallet(walletFile)
        self.peerList = Params.PEERS  #Peer.init_peers(Params.PEERS_FILE)
コード例 #3
0
    def __init__(self):

        # active_chain is initialized with a chain index and a list with genesis block in it
        self.active_chain: BlockChain = BlockChain(
            idx=Params.ACTIVE_CHAIN_IDX, chain=[Block.genesis_block()])
        self.side_branches: Iterable[BlockChain] = []
        self.orphan_blocks: Iterable[Block] = []
        self.utxo_set: UTXO_Set = UTXO_Set()
        self.mempool: MemPool = MemPool()
        self.wallet: Wallet = Wallet.init_wallet(Params.WALLET_FILE)

        # PeerManager use Peer.init_peer() to read peer from PEERS_FILE or peer list in Params.py
        self.peerManager: PeerManager = PeerManager(
            Peer.init_peers(Params.PEERS_FILE))

        self.mine_interrupt: threading.Event = threading.Event()
        self.ibd_done: threading.Event = threading.Event()
        self.chain_lock: threading.RLock = threading.RLock()
        self.peers_lock: threading.RLock = threading.RLock()

        self.gs = dict()
        (
            self.gs["Block"],
            self.gs["Transaction"],
            self.gs["UnspentTxOut"],
            self.gs["Message"],
            self.gs["TxIn"],
            self.gs["TxOut"],
            self.gs["Peer"],
            self.gs["OutPoint"],
        ) = (
            globals()["Block"],
            globals()["Transaction"],
            globals()["UnspentTxOut"],
            globals()["Message"],
            globals()["TxIn"],
            globals()["TxOut"],
            globals()["Peer"],
            globals()["OutPoint"],
        )
コード例 #4
0
    def __init__(self):

        self.active_chain: BlockChain = BlockChain(
            idx=Params.ACTIVE_CHAIN_IDX, chain=[Block.genesis_block()])
        self.side_branches: Iterable[BlockChain] = []
        self.orphan_blocks: Iterable[Block] = []
        self.utxo_set: UTXO_Set = UTXO_Set()
        self.mempool: MemPool = MemPool()
        self.wallet: Wallet = Wallet.init_wallet(Params.WALLET_FILE)

        #self.peers: Iterable[Peer] = Peer.init_peers(Params.PEERS_FILE)
        self.peerManager: PeerManager = PeerManager(
            Peer.init_peers(Params.PEERS_FILE))

        self.mine_interrupt: threading.Event = threading.Event()
        self.ibd_done: threading.Event = threading.Event()
        self.chain_lock: _thread.RLock = threading.RLock()
        self.peers_lock: _thread.RLock = threading.RLock()

        self.gs = dict()
        self.gs['Block'], self.gs['Transaction'], self.gs['UnspentTxOut'], self.gs['Message'], self.gs['TxIn'], self.gs['TxOut'], self.gs['Peer'], self.gs['OutPoint']= \
                    globals()['Block'], globals()['Transaction'], globals()['UnspentTxOut'], globals()['Message'], \
                    globals()['TxIn'], globals()['TxOut'], globals()['Peer'], globals()['OutPoint']
コード例 #5
0
ファイル: Transaction.py プロジェクト: SouthWa11/EdgenceChain
        def validate_signature_for_spend(txin, utxo: UnspentTxOut):
            def build_spend_message(to_spend, pk, sequence, txouts) -> bytes:
                """This should be ~roughly~ equivalent to SIGHASH_ALL."""
                return Utils.sha256d(
                    Utils.serialize(to_spend) + str(sequence) +
                    binascii.hexlify(pk).decode() +
                    Utils.serialize(txouts)).encode()

            pubkey_as_addr = Wallet.pubkey_to_address(txin.unlock_pk)
            verifying_key = ecdsa.VerifyingKey.from_string(
                txin.unlock_pk, curve=ecdsa.SECP256k1)

            if pubkey_as_addr != utxo.to_address:
                raise TxUnlockError("Pubkey doesn't match")

            try:
                spend_msg = build_spend_message(txin.to_spend, txin.unlock_pk,
                                                txin.sequence, self.txouts)
                verifying_key.verify(txin.unlock_sig, spend_msg)
            except Exception:
                logger.exception(f'[ds] Key verification failed')
                raise TxUnlockError("Signature doesn't match")
            return True
コード例 #6
0
ファイル: Market.py プロジェクト: yann-soliman/pyTrade
class Market:
    def __init__(self):
        self.logger = Logger().get_logger()
        self.wallet = Wallet()

    def add_euro_on_wallet(self, amount):
        self.logger.info("[+] Ajout de %s euro dans le wallet", amount)
        self.wallet.plus(Euro(amount))

    def buy(self, money_amount, money_price):
        """
         Achète money_amount au prix de money_price l'unité
        :param money1: la Money à acheter
        :param money2: prix de la Money avec laquelle faire l'échange
        :return: void
        """
        if money_amount.amount <= 0:
            self.logger.error("Impossible d'acheter %s", money_amount)
            return
        if money_price.amount <= 0:
            self.logger.error("Impossible d'acheter %s car le prix d'achat est trop faible", money_amount)
            return

        # Conversion
        money_to_sell = ExchangeRateCalculator.convert(money_amount, money_price)

        # Si le wallet a assez de fond pour acheter
        if self.wallet.has_enough_funds(money_to_sell):
            self.logger.info("J'achète %s au prix de %s l'unité", money_amount, money_price)
            self.wallet.minus(money_to_sell)
            self.wallet.plus(money_amount)
        else:
            self.logger.error("Impossible d'acheter %s. Seulement %s disponible dans le wallet.", money_amount,
                              self.wallet.get_balance(money_price.currency))

    def buy_all(self, currency, money_price):
        """
        Dépense toute la thune possible du wallet pour acheter la devise au prix indiqué
        :param currency: devise à acheter
        :param money_price: prix pour une unité
        :return:
        """
        total_money_in_wallet = self.get_balance(money_price.currency)
        if total_money_in_wallet.amount > 0:
            # TODO : Quelle est la bonne façon d'instancier un Money à partir de sa devise ???
            money_to_buy = MoneyDeserializer.deserialize(currency)
            money_to_buy.amount = total_money_in_wallet.amount / money_price.amount
            self.buy(money_to_buy, money_price)
        else:
            self.logger.error("Fonds insufisant pour acheter.")

    def sell(self, money_amount, money_price):
        """
         Vend money_amount au prix de money_price l'unité
        :param money1: la Money à vendre
        :param money2: prix de la Money avec laquelle faire l'échange
        :return: void
        """
        if money_amount.amount <= 0:
            self.logger.error("Impossible de vendre %s", money_amount)
            return
        if money_price.amount <= 0:
            self.logger.error("Impossible de vendre %s car le prix d'achat est trop faible", money_amount)
            return
        # Si on a assez de fond de ce qu'on souhaite vendre dans le wallet
        if self.wallet.has_enough_funds(money_amount):
            self.logger.info("Je vends %s au prix de %s l'unité", money_amount, money_price)
            # Conversion
            money_to_buy = ExchangeRateCalculator.convert(money_amount, money_price)
            self.wallet.minus(money_amount)
            self.wallet.plus(money_to_buy)
        else:
            self.logger.error("Impossible de vendre %s . Seulement %s disponible dans le wallet.", money_amount,
                              self.wallet.get_balance(money_price.currency))

    def sell_all(self, currency, money_price):
        """
        Bazarde toutes les devises possibles du wallet pour vendre la devise au prix indiqué
        :param currency: devise à vendre
        :param money_price: prix pour une unité
        :return:
        """
        total_money_in_wallet = self.get_balance(currency)
        if total_money_in_wallet.amount > 0:
            self.sell(total_money_in_wallet, money_price)
        else:
            self.logger.warning("Rien à vendre.")

    def print_balance(self):
        self.wallet.print_balance()

    def get_balance(self, currency):
        return copy.copy(self.wallet.get_balance(currency))

    def has_money_in_wallet(self):
        return self.wallet.has_moneys()
コード例 #7
0
ファイル: Market.py プロジェクト: yann-soliman/pyTrade
 def __init__(self):
     self.logger = Logger().get_logger()
     self.wallet = Wallet()