Esempio n. 1
0
    def test_file_read_write(self):
        # get suggested parameters and fee
        params = self.acl.suggested_params()
        gh = params["genesishashb64"]
        last_round = params["lastRound"]
        fee = params["fee"]

        # create transaction
        txn = transaction.PaymentTxn(self.account_0, fee, last_round,
                                     last_round + 100, gh, self.account_0,
                                     1000)

        # get private key
        w = wallet.Wallet(wallet_name, wallet_pswd, self.kcl)
        private_key = w.export_key(self.account_0)

        # sign transaction
        stx = txn.sign(private_key)

        # write to file
        dir_path = os.path.dirname(os.path.realpath(__file__))
        transaction.write_to_file([txn, stx], dir_path + "/raw.tx")

        # read from file
        txns = transaction.retrieve_from_file(dir_path + "/raw.tx")

        # check that the transactions are still the same
        self.assertEqual(encoding.msgpack_encode(txn),
                         encoding.msgpack_encode(txns[0]))
        self.assertEqual(encoding.msgpack_encode(stx),
                         encoding.msgpack_encode(txns[1]))

        # delete the file
        os.remove("raw.tx")
Esempio n. 2
0
    def test_file_read_write(self):
        # get suggested parameters and fee
        gh = self.acl.versions()['genesis_hash_b64']
        rnd = int(self.acl.status()['lastRound'])
        sp = transaction.SuggestedParams(0, rnd, rnd + 100, gh)

        # create transaction
        txn = transaction.PaymentTxn(self.account_0, sp, self.account_0, 1000)

        # get private key
        w = wallet.Wallet(wallet_name, wallet_pswd, self.kcl)
        private_key = w.export_key(self.account_0)

        # sign transaction
        stx = txn.sign(private_key)

        # write to file
        dir_path = os.path.dirname(os.path.realpath(__file__))
        transaction.write_to_file([txn, stx], dir_path + "/raw.tx")

        # read from file
        txns = transaction.retrieve_from_file(dir_path + "/raw.tx")

        # check that the transactions are still the same
        self.assertEqual(encoding.msgpack_encode(txn),
                         encoding.msgpack_encode(txns[0]))
        self.assertEqual(encoding.msgpack_encode(stx),
                         encoding.msgpack_encode(txns[1]))

        # delete the file
        os.remove("raw.tx")
Esempio n. 3
0
def check_enc(context):
    dir_path = os.path.dirname(os.path.realpath(__file__))
    dir_path = os.path.dirname(os.path.dirname(dir_path))
    new = transaction.retrieve_from_file(dir_path + "/temp/raw" + context.num +
                                         ".tx")
    old = transaction.retrieve_from_file(dir_path + "/temp/old" + context.num +
                                         ".tx")
    assert encoding.msgpack_encode(new[0]) == encoding.msgpack_encode(old[0])
    def test_transaction_group(self):
        # get the default wallet
        wallets = self.kcl.list_wallets()
        wallet_id = None
        for w in wallets:
            if w["name"] == wallet_name:
                wallet_id = w["id"]

        # get a new handle for the wallet
        handle = self.kcl.init_wallet_handle(wallet_id, wallet_pswd)

        # get private key
        private_key_0 = self.kcl.export_key(handle, wallet_pswd,
                                            self.account_0)

        # get suggested parameters and fee
        params = self.acl.suggested_params()
        gen = params["genesisID"]
        gh = params["genesishashb64"]
        last_round = params["lastRound"]
        fee = params["fee"]

        # create transaction
        txn = transaction.PaymentTxn(self.account_0,
                                     fee,
                                     last_round,
                                     last_round + 100,
                                     gh,
                                     self.account_0,
                                     1000,
                                     gen=gen)

        # calculate group id
        gid = transaction.calculate_group_id([txn])
        txn.group = gid

        # sign using kmd
        stxn1 = self.kcl.sign_transaction(handle, wallet_pswd, txn)
        # sign using transaction call
        stxn2 = txn.sign(private_key_0)
        # check that they are the same
        self.assertEqual(encoding.msgpack_encode(stxn1),
                         encoding.msgpack_encode(stxn2))

        try:
            send = self.acl.send_transactions([stxn1])
            self.assertEqual(send, txn.get_txid())
        except error.AlgodHTTPError as ex:
            self.assertIn(
                "TransactionPool.Remember: transaction groups not supported",
                str(ex))
Esempio n. 5
0
 def test_serialize_zero_amt(self):
     address = "7ZUECA7HFLZTXENRV24SHLU4AVPUTMTTDUFUBNBD64C73F3UHRTHAIOF6Q"
     gh = "JgsgCaCTqIaLeVhyL6XlRu3n7Rfk2FxMeK+wRSaQ7dI="
     txn = transaction.PaymentTxn(address,
                                  3,
                                  1,
                                  100,
                                  gh,
                                  address,
                                  0,
                                  note=bytes([1, 32, 200]))
     enc = encoding.msgpack_encode(txn)
     re_enc = encoding.msgpack_encode(encoding.msgpack_decode(enc))
     self.assertEqual(enc, re_enc)
Esempio n. 6
0
 def test_serialize_gen(self):
     address = "7ZUECA7HFLZTXENRV24SHLU4AVPUTMTTDUFUBNBD64C73F3UHRTHAIOF6Q"
     gh = "JgsgCaCTqIaLeVhyL6XlRu3n7Rfk2FxMeK+wRSaQ7dI="
     txn = transaction.PaymentTxn(address,
                                  3,
                                  1,
                                  100,
                                  gh,
                                  address,
                                  1000,
                                  gen="testnet-v1.0",
                                  close_remainder_to=address)
     enc = encoding.msgpack_encode(txn)
     re_enc = encoding.msgpack_encode(encoding.msgpack_decode(enc))
     self.assertEqual(enc, re_enc)
Esempio n. 7
0
 def test_sign(self):
     mn = ("advice pudding treat near rule blouse same whisper inner " +
           "electric quit surface sunny dismiss leader blood seat " +
           "clown cost exist hospital century reform able sponsor")
     gh = "JgsgCaCTqIaLeVhyL6XlRu3n7Rfk2FxMeK+wRSaQ7dI="
     address = "PNWOET7LLOWMBMLE4KOCELCX6X3D3Q4H2Q4QJASYIEOF7YIPPQBG3YQ5YI"
     close = "IDUTJEUIEVSMXTU4LGTJWZ2UE2E6TIODUKU6UW3FU3UKIQQ77RLUBBBFLA"
     sk = mnemonic.to_private_key(mn)
     pk = account.address_from_private_key(sk)
     txn = transaction.PaymentTxn(pk,
                                  4,
                                  12466,
                                  13466,
                                  gh,
                                  address,
                                  1000,
                                  note=base64.b64decode("6gAVR0Nsv5Y="),
                                  gen="devnet-v33.0",
                                  close_remainder_to=close)
     stx = txn.sign(sk)
     golden = ("gqNzaWfEQPhUAZ3xkDDcc8FvOVo6UinzmKBCqs0woYSfodlmBMfQvGbeU" +
               "x3Srxy3dyJDzv7rLm26BRv9FnL2/AuT7NYfiAWjdHhui6NhbXTNA+ilY2" +
               "xvc2XEIEDpNJKIJWTLzpxZpptnVCaJ6aHDoqnqW2Wm6KRCH/xXo2ZlZc0" +
               "EmKJmds0wsqNnZW6sZGV2bmV0LXYzMy4womdoxCAmCyAJoJOohot5WHIv" +
               "peVG7eftF+TYXEx4r7BFJpDt0qJsds00mqRub3RlxAjqABVHQ2y/lqNyY" +
               "3bEIHts4k/rW6zAsWTinCIsV/X2PcOH1DkEglhBHF/hD3wCo3NuZMQg5/" +
               "D4TQaBHfnzHI2HixFV9GcdUaGFwgCQhmf0SVhwaKGkdHlwZaNwYXk=")
     self.assertEqual(golden, encoding.msgpack_encode(stx))
     txid_golden = "5FJDJD5LMZC3EHUYYJNH5I23U4X6H2KXABNDGPIL557ZMJ33GZHQ"
     self.assertEqual(txn.get_txid(), txid_golden)
Esempio n. 8
0
 def test_payment_txn(self):
     paytxn = ("iaNhbXTOAAGGoKNmZWXNA+iiZnbNcq2jZ2Vuq25ldHdvcmstdjM4omdo" +
               "xCBN/+nfiNPXLbuigk8M/TXsMUfMK7dV//xB1wkoOhNu9qJsds1zEaNy" +
               "Y3bEIAZ2cvp4J0OiBy5eAHIX/njaRko955rEdN4AUNEl4rxTo3NuZMQg" +
               "GC5kQiOIPooA8mrvoHRyFtk27F/PPN08bAufGhnp0BGkdHlwZaNwYXk=")
     self.assertEqual(
         paytxn, encoding.msgpack_encode(encoding.msgpack_decode(paytxn)))
def write_multisig_signed_transaction_to_file():
    algod_client = connect_to_network()
    # Change these values with mnemonics
    # mnemonic1 = "PASTE phrase for account 1"
    # mnemonic2 = "PASTE phrase for account 2"
    # mnemonic3 = "PASTE phrase for account 3"

    mnemonic1 = "patrol target joy dial ethics flip usual fatigue bulb security prosper brand coast arch casino burger inch cricket scissors shoe evolve eternal calm absorb school"
    mnemonic2 = "genius inside turtle lock alone blame parent civil depend dinosaur tag fiction fun skill chief use damp daughter expose pioneer today weasel box about silly"
    mnemonic3 = "off canyon mystery cable pluck emotion manual legal journey grit lunch include friend social monkey approve lava steel school mango auto cactus huge ability basket"

    # For ease of reference, add account public and private keys to
    # an accounts dict.

    private_key_1 = mnemonic.to_private_key(mnemonic1)
    account_1 = mnemonic.to_public_key(mnemonic1)

    private_key_2 = mnemonic.to_private_key(mnemonic2)
    account_2 = mnemonic.to_public_key(mnemonic2)

    private_key_3 = mnemonic.to_private_key(mnemonic3)
    account_3 = mnemonic.to_public_key(mnemonic3)
    # create a multisig account
    version = 1  # multisig version
    threshold = 2  # how many signatures are necessary
    msig = Multisig(version, threshold, [account_1, account_2])

    print("Multisig Address: ", msig.address())
    print(
        "Please go to: https://bank.testnet.algorand.network/ to fund multisig account.",
        msig.address())
    # input("Please go to: https://bank.testnet.algorand.network/ to fund multisig account." + '\n' + "Press Enter to continue...")

    # get suggested parameters
    params = algod_client.suggested_params()
    # comment out the next two (2) lines to use suggested fees
    # params.flat_fee = True
    # params.fee = 1000

    # create a transaction
    sender = msig.address()
    recipient = account_3
    amount = 10000
    note = "Hello Multisig".encode()
    txn = PaymentTxn(sender, params, recipient, amount, None, note, None)

    # create a SignedTransaction object
    mtx = MultisigTransaction(txn, msig)

    # sign the transaction
    mtx.sign(private_key_1)
    mtx.sign(private_key_2)

    # print encoded transaction
    print(encoding.msgpack_encode(mtx))

    # write to file
    dir_path = os.path.dirname(os.path.realpath(__file__))
    transaction.write_to_file([mtx], dir_path + "/signed.mtx")
    print("Signed mtx file saved!")
Esempio n. 10
0
 def test_bid(self):
     bid = ("gqFigqNiaWSGo2FpZAGjYXVjxCCokNFWl9DCqHrP9trjPICAMGOaRoX/OR+" +
            "M6tHWhfUBkKZiaWRkZXLEIP1rCXe2x5+exPBfU3CZwGPMY8mzwvglET+Qtg" +
            "fCPdCmo2N1cs8AAADN9kTOAKJpZM5JeDcCpXByaWNlzQMgo3NpZ8RAiR06J" +
            "4suAixy13BKHlw4VrORKzLT5CJr9n3YSj0Ao6byV23JHGU0yPf7u9/o4ECw" +
            "4Xy9hc9pWopLW97xKXRfA6F0oWI=")
     self.assertEqual(bid,
                      encoding.msgpack_encode(encoding.msgpack_decode(bid)))
Esempio n. 11
0
def write_drr(res, contents):
    dir_path = os.path.dirname(os.path.realpath(__file__))
    path = os.path.join(dir_path, res)
    data = encoding.msgpack_encode(contents)
    data = base64.b64decode(data)
    with open(path, "wb") as fout:
        fout.write(data)
    return
Esempio n. 12
0
 def test_signed_txn(self):
     stxn = ("gqNzaWfEQGdpjnStb70k2iXzOlu+RSMgCYLe25wkUfbgRsXs7jx6rbW61i" +
             "vCs6/zGs3gZAZf4L2XAQak7OjMh3lw9MTCIQijdHhuiaNhbXTOAAGGoKNm" +
             "ZWXNA+iiZnbNcl+jZ2Vuq25ldHdvcmstdjM4omdoxCBN/+nfiNPXLbuigk" +
             "8M/TXsMUfMK7dV//xB1wkoOhNu9qJsds1yw6NyY3bEIPRUuVDPVUFC7Jk3" +
             "+xDjHJfwWFDp+Wjy+Hx3cwL9ncVYo3NuZMQgGC5kQiOIPooA8mrvoHRyFt" +
             "k27F/PPN08bAufGhnp0BGkdHlwZaNwYXk=")
     self.assertEqual(
         stxn, encoding.msgpack_encode(encoding.msgpack_decode(stxn)))
Esempio n. 13
0
 def test_keyreg_txn(self):
     keyregtxn = ("jKNmZWXNA+iiZnbNcoqjZ2Vuq25ldHdvcmstdjM4omdoxCBN/+nfi" +
                  "NPXLbuigk8M/TXsMUfMK7dV//xB1wkoOhNu9qJsds1y7qZzZWxrZX" +
                  "nEIBguZEIjiD6KAPJq76B0chbZNuxfzzzdPGwLnxoZ6dARo3NuZMQ" +
                  "gGC5kQiOIPooA8mrvoHRyFtk27F/PPN08bAufGhnp0BGkdHlwZaZr" +
                  "ZXlyZWendm90ZWZzdM1yiqZ2b3Rla2TNMDmndm90ZWtlecQgGC5kQ" +
                  "iOIPooA8mrvoHRyFtk27F/PPN08bAufGhnp0BGndm90ZWxzdM1y7g==")
     self.assertEqual(
         keyregtxn,
         encoding.msgpack_encode(encoding.msgpack_decode(keyregtxn)))
Esempio n. 14
0
 def test_assetconfig_txn(self):
     actxn = ("iKRhcGFyhKFjxCAJ+9J2LAj4bFrmv23Xp6kB3mZ111Dgfoxcdphkfbbh" +
              "/aFmxCAJ+9J2LAj4bFrmv23Xp6kB3mZ111Dgfoxcdphkfbbh/aFtxCAJ" +
              "+9J2LAj4bFrmv23Xp6kB3mZ111Dgfoxcdphkfbbh/aFyxCAJ+9J2LAj4" +
              "bFrmv23Xp6kB3mZ111Dgfoxcdphkfbbh/aRjYWlkgqFjxCAJ+9J2LAj4" +
              "bFrmv23Xp6kB3mZ111Dgfoxcdphkfbbh/aFpzQTSo2ZlZc0OzqJmds4A" +
              "BOwPomdoxCBIY7UYpLPITsgQ8i1PEIHLD3HwWaesIN7GL39w5Qk6IqJs" +
              "ds4ABO/3o3NuZMQgCfvSdiwI+Gxa5r9t16epAd5mdddQ4H6MXHaYZH22" +
              "4f2kdHlwZaRhY2Zn")
     self.assertEqual(
         actxn, encoding.msgpack_encode(encoding.msgpack_decode(actxn)))
Esempio n. 15
0
    def test_serialize_txgroup(self):
        address = "7ZUECA7HFLZTXENRV24SHLU4AVPUTMTTDUFUBNBD64C73F3UHRTHAIOF6Q"
        gh = "JgsgCaCTqIaLeVhyL6XlRu3n7Rfk2FxMeK+wRSaQ7dI="
        txn = transaction.PaymentTxn(address,
                                     3,
                                     1,
                                     100,
                                     gh,
                                     address,
                                     1000,
                                     gen="testnet-v1.0",
                                     close_remainder_to=address)
        txid = txn.get_txid().encode()
        txid = base64.decodebytes(txid)

        txgroup = transaction.TxGroup([txid])
        enc = encoding.msgpack_encode(txgroup)
        re_enc = encoding.msgpack_encode(encoding.msgpack_decode(enc))
        self.assertEqual(enc, re_enc)

        txgroup = transaction.TxGroup([txid] * 11)
        enc = encoding.msgpack_encode(txgroup)
        re_enc = encoding.msgpack_encode(encoding.msgpack_decode(enc))
        self.assertEqual(enc, re_enc)

        # check group field serialization
        gid = transaction.calculate_group_id([txn, txn])
        txn.group = gid
        enc = encoding.msgpack_encode(txn)
        re_enc = encoding.msgpack_encode(encoding.msgpack_decode(enc))
        self.assertEqual(enc, re_enc)
Esempio n. 16
0
 def test_multisig_txn(self):
     msigtxn = ("gqRtc2lng6ZzdWJzaWeSgqJwa8Qg1ke3gkLuR0MUN/Ku0oyiRVIm9P1" +
                "QFDaiEhT5vtfLmd+hc8RAIEbfnhccjWfYQFQp/P4aJjATFdgaDDpnhy" +
                "JF0tU/37CO5I5hhoCvUCRH/A/6X94Ewz9YEtk5dANEGKQW+/WyAIKic" +
                "GvEIKgAZfZ4iDC+UY/P5F3tgs5rqeyYt08LT0c/D78u0V7KoXPEQCxU" +
                "kQgTVC9lLpKVzcZGKesSCQcZL9UjXTzrteADicvcca7KT3WP0crGgAf" +
                "J3a17Na5cykJzFEn7pq2SHgwD/QujdGhyAqF2AaN0eG6Jo2FtdM0D6K" +
                "NmZWXNA+iiZnbNexSjZ2Vuq25ldHdvcmstdjM4omdoxCBN/+nfiNPXL" +
                "buigk8M/TXsMUfMK7dV//xB1wkoOhNu9qJsds17eKNyY3bEIBguZEIj" +
                "iD6KAPJq76B0chbZNuxfzzzdPGwLnxoZ6dARo3NuZMQgpuIJvJzW8E4" +
                "uxsQGCW0S3n1u340PbHTB2zhtXo/AiI6kdHlwZaNwYXk=")
     self.assertEqual(
         msigtxn, encoding.msgpack_encode(encoding.msgpack_decode(msigtxn)))
Esempio n. 17
0
    def test_auction(self):
        # get the default wallet
        wallets = self.kcl.list_wallets()
        wallet_id = None
        for w in wallets:
            if w["name"] == wallet_name:
                wallet_id = w["id"]

        # get a new handle for the wallet
        handle = self.kcl.init_wallet_handle(wallet_id, wallet_pswd)

        # generate account with kmd
        account_1 = self.kcl.generate_key(handle, False)

        # get suggested parameters and fee
        params = self.acl.suggested_params()
        gen = params["genesisID"]
        gh = params["genesishashb64"]
        last_round = params["lastRound"]
        fee = params["fee"]

        # get self.account_0 private key
        private_key_0 = self.kcl.export_key(handle, wallet_pswd,
                                            self.account_0)

        # create bid
        bid = auction.Bid(self.account_0, 10000, 260, "bid_id", account_1,
                          "auc_id")
        sb = bid.sign(private_key_0)
        nf = auction.NoteField(sb, constants.note_field_type_bid)

        # create transaction
        txn = transaction.PaymentTxn(self.account_0,
                                     fee,
                                     last_round,
                                     last_round + 100,
                                     gh,
                                     account_1,
                                     100000,
                                     note=base64.b64decode(
                                         encoding.msgpack_encode(nf)),
                                     gen=gen)

        # sign transaction with account
        signed_account = txn.sign(private_key_0)

        # send transaction
        send = self.acl.send_transaction(signed_account)
        self.assertEqual(send, txn.get_txid())
        del_1 = self.kcl.delete_key(handle, wallet_pswd, account_1)
        self.assertTrue(del_1)
def read_multisig_unsigned_transaction_from_file():
    algod_client = connect_to_network()
    # Change these values with mnemonics
    # mnemonic1 = "PASTE phrase for account 1"
    # mnemonic2 = "PASTE phrase for account 2"
    # mnemonic3 = "PASTE phrase for account 3"

    mnemonic1 = "patrol target joy dial ethics flip usual fatigue bulb security prosper brand coast arch casino burger inch cricket scissors shoe evolve eternal calm absorb school"
    mnemonic2 = "genius inside turtle lock alone blame parent civil depend dinosaur tag fiction fun skill chief use damp daughter expose pioneer today weasel box about silly"
    mnemonic3 = "off canyon mystery cable pluck emotion manual legal journey grit lunch include friend social monkey approve lava steel school mango auto cactus huge ability basket"

    # For ease of reference, add account public and private keys to
    # an accounts dict.

    private_key_1 = mnemonic.to_private_key(mnemonic1)
    account_1 = mnemonic.to_public_key(mnemonic1)

    private_key_2 = mnemonic.to_private_key(mnemonic2)
    account_2 = mnemonic.to_public_key(mnemonic2)

    private_key_3 = mnemonic.to_private_key(mnemonic3)
    account_3 = mnemonic.to_public_key(mnemonic3)

    print("Account 1 address: {}".format(account_1))
    print("Account 2 address: {}".format(account_2))
    print("Account 3 address: {}".format(account_3))

    # read from file
    dir_path = os.path.dirname(os.path.realpath(__file__))
    msigs = transaction.retrieve_from_file(dir_path + "/unsigned.mtx")
    mtx = msigs[0]

    # sign the transaction
    mtx.sign(private_key_1)
    mtx.sign(private_key_2)

    # send the transaction
    txid = algod_client.send_raw_transaction(encoding.msgpack_encode(mtx))
    # wait for confirmation
    try:
        confirmed_txn = wait_for_confirmation(algod_client, txid, 4)
        print("TXID: ", txid)
        print("Result confirmed in round: {}".format(
            confirmed_txn['confirmed-round']))
        print("Transaction information: {}".format(
            json.dumps(confirmed_txn, indent=4)))
        print("Decoded note: {}".format(
            base64.b64decode(confirmed_txn["txn"]["txn"]["note"]).decode()))
    except Exception as err:
        print(err)
Esempio n. 19
0
    def save_dryrun_request(name_or_fp, req):
        """Helper function to save dryrun request

        Args:
            name_or_fp (str, file-like): filename or fp to save the request to
            req (DryrunRequest): dryrun request object to save
        """
        need_close = False
        if isinstance(name_or_fp, str):
            fp = open(name_or_fp, "wb")
            need_close = True
        else:
            fp = name_or_fp

        data = msgpack_encode(req)
        data = base64.b64decode(data)

        fp.write(data)
        if need_close:
            fp.close()
Esempio n. 20
0
def read_multisig_signed_transaction_from_file():
    algod_client = connect_to_network()
    
    # read from file
    dir_path = os.path.dirname(os.path.realpath(__file__))
    msigs = transaction.retrieve_from_file(dir_path + "/signed.mtx")
    mtx = msigs[0]

    try:
    # send the transaction
        txid = algod_client.send_raw_transaction(
        encoding.msgpack_encode(mtx))        
         # wait for confirmation	       
        confirmed_txn = wait_for_confirmation(algod_client, txid, 4)  
        print("Transaction information: {}".format(
            json.dumps(confirmed_txn, indent=4)))
        print("Decoded note: {}".format(base64.b64decode(
            confirmed_txn["txn"]["txn"]["note"]).decode()))
    except Exception as err:
        print(err)
Esempio n. 21
0
    def test_sign(self):
        msig = transaction.Multisig(1, 2, [
            "DN7MBMCL5JQ3PFUQS7TMX5AH4EEKOBJVDUF4TCV6WERATKFLQF4MQUPZTA",
            "BFRTECKTOOE7A5LHCF3TTEOH2A7BW46IYT2SX5VP6ANKEXHZYJY77SJTVM",
            "47YPQTIGQEO7T4Y4RWDYWEKV6RTR2UNBQXBABEEGM72ESWDQNCQ52OPASU"
        ])
        mn = ("advice pudding treat near rule blouse same whisper inner " +
              "electric quit surface sunny dismiss leader blood seat clown " +
              "cost exist hospital century reform able sponsor")
        sk = mnemonic.to_private_key(mn)

        rcv = "PNWOET7LLOWMBMLE4KOCELCX6X3D3Q4H2Q4QJASYIEOF7YIPPQBG3YQ5YI"
        gh = "JgsgCaCTqIaLeVhyL6XlRu3n7Rfk2FxMeK+wRSaQ7dI="
        close = "IDUTJEUIEVSMXTU4LGTJWZ2UE2E6TIODUKU6UW3FU3UKIQQ77RLUBBBFLA"
        txn = transaction.PaymentTxn(msig.address(),
                                     4,
                                     12466,
                                     13466,
                                     gh,
                                     rcv,
                                     1000,
                                     note=base64.b64decode("X4Bl4wQ9rCo="),
                                     gen="devnet-v33.0",
                                     close_remainder_to=close)
        mtx = transaction.MultisigTransaction(txn, msig)
        mtx.sign(sk)
        golden = ("gqRtc2lng6ZzdWJzaWeTgaJwa8QgG37AsEvqYbeWkJfmy/QH4QinBTUdC" +
                  "8mKvrEiCairgXiBonBrxCAJYzIJU3OJ8HVnEXc5kcfQPhtzyMT1K/av8B" +
                  "qiXPnCcYKicGvEIOfw+E0GgR358xyNh4sRVfRnHVGhhcIAkIZn9ElYcGi" +
                  "hoXPEQF6nXZ7CgInd1h7NVspIPFZNhkPL+vGFpTNwH3Eh9gwPM8pf1EPT" +
                  "HfPvjf14sS7xN7mTK+wrz7Odhp4rdWBNUASjdGhyAqF2AaN0eG6Lo2Ftd" +
                  "M0D6KVjbG9zZcQgQOk0koglZMvOnFmmm2dUJonpocOiqepbZabopEIf/F" +
                  "ejZmVlzQSYomZ2zTCyo2dlbqxkZXZuZXQtdjMzLjCiZ2jEICYLIAmgk6i" +
                  "Gi3lYci+l5Ubt5+0X5NhcTHivsEUmkO3Somx2zTSapG5vdGXECF+AZeME" +
                  "Pawqo3JjdsQge2ziT+tbrMCxZOKcIixX9fY9w4fUOQSCWEEcX+EPfAKjc" +
                  "25kxCCNkrSJkAFzoE36Q1mjZmpq/OosQqBd2cH3PuulR4A36aR0eXBlo3" +
                  "BheQ==")
        self.assertEqual(golden, encoding.msgpack_encode(mtx))
        txid_golden = "TDIO6RJWJIVDDJZELMSX5CPJW7MUNM3QR4YAHYAKHF3W2CFRTI7A"
        self.assertEqual(txn.get_txid(), txid_golden)
Esempio n. 22
0
 def test_serialize_assetconfig(self):
     address = "BH55E5RMBD4GYWXGX5W5PJ5JAHPGM5OXKDQH5DC4O2MGI7NW4H6VOE4CP4"
     gh = "SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI="
     txn = transaction.AssetConfigTxn(address,
                                      10,
                                      322575,
                                      323575,
                                      gh,
                                      address,
                                      1234,
                                      manager=address,
                                      reserve=address,
                                      freeze=address,
                                      clawback=address)
     golden = ("iKRhcGFyhKFjxCAJ+9J2LAj4bFrmv23Xp6kB3mZ111Dgfoxcdphkfbbh" +
               "/aFmxCAJ+9J2LAj4bFrmv23Xp6kB3mZ111Dgfoxcdphkfbbh/aFtxCAJ" +
               "+9J2LAj4bFrmv23Xp6kB3mZ111Dgfoxcdphkfbbh/aFyxCAJ+9J2LAj4" +
               "bFrmv23Xp6kB3mZ111Dgfoxcdphkfbbh/aRjYWlkgqFjxCAJ+9J2LAj4" +
               "bFrmv23Xp6kB3mZ111Dgfoxcdphkfbbh/aFpzQTSo2ZlZc0OzqJmds4A" +
               "BOwPomdoxCBIY7UYpLPITsgQ8i1PEIHLD3HwWaesIN7GL39w5Qk6IqJs" +
               "ds4ABO/3o3NuZMQgCfvSdiwI+Gxa5r9t16epAd5mdddQ4H6MXHaYZH22" +
               "4f2kdHlwZaRhY2Zn")
     self.assertEqual(encoding.msgpack_encode(txn), golden)
Esempio n. 23
0
def enc_dec_bid(context):
    context.bid = encoding.msgpack_decode(encoding.msgpack_encode(context.bid))
Esempio n. 24
0
def sign_msig_both_equal(context):
    assert encoding.msgpack_encode(context.mtx) == encoding.msgpack_encode(
        context.mtx_kmd)
Esempio n. 25
0
def msig_eq(context):
    assert encoding.msgpack_encode(context.msig) == encoding.msgpack_encode(
        context.exp)
Esempio n. 26
0
def equal_msig_golden(context, golden):
    if not encoding.msgpack_encode(context.mtx) == golden:
        print(encoding.msgpack_encode(context.mtx))
        print(golden)
    assert encoding.msgpack_encode(context.mtx) == golden
Esempio n. 27
0
def equal_golden(context, golden):
    assert encoding.msgpack_encode(context.stx) == golden
Esempio n. 28
0
def match_setup(algod_client, dealer_passphrase, addr_opponent,
                match_hours_timeout, microalgo_bet_amount, asa_pieces_total,
                asa_pieces_max_remove):
    """HELP match_setup:
        (AlgodClient, str, str, float, int, int, int) - Sets up a new AlgoNim
        match.
    """

    # AlgoNim Players
    # Palyer 1 (Dealer) - Match Set Up costs about: 0.8 ALGO
    dealer = {
        'pk': mnemonic.to_public_key(dealer_passphrase),
        'sk': mnemonic.to_private_key(dealer_passphrase)
    }

    # Player 2 (Opponent) - Must Opt-In AlgoNim ASAs to play the match
    opponent = {'pk': addr_opponent}

    print("                                                               ")
    print("      _       __                 ____  _____   _               ")
    print("     / \     [  |               |_   \|_   _| (_)              ")
    print("    / _ \     | |  .--./)  .--.   |   \ | |   __   _ .--..--.  ")
    print("   / ___ \    | | / /'`\;/ .'`\ \ | |\ \| |  [  | [ `.-. .-. | ")
    print(" _/ /   \ \_  | | \ \._//| \__. |_| |_\   |_  | |  | | | | | | ")
    print("|____| |____|[___].',__`  '.__.'|_____|\____|[___][___||__||__]")
    print("                 ( ( __))                                      ")
    print("                                                       by cusma")
    print("                                                               ")
    print("  Welcome to AlgoNim, the first crypto-mini-game on Algorand!  ")

    # Asset Create: AlgoNim ASA Pieces
    print("")
    print("Dealer creating AlgoNim ASA Piece for this match...")
    asa_pieces_id = asa_pieces_create(algod_client, dealer, asa_pieces_total)

    # Asset Create: AlgoNim ASA Turn
    print("")
    print("Dealer creating AlgoNim ASA Turn for this match...")
    asa_turn_id = asa_turn_create(algod_client, dealer)

    # TEAL: AlgoNim ASC1 Sink
    print("")
    print("Dealer writing AlgoNim ASC1 Sink TEAL for this match...")
    asc1_sink_source = asc1_sink_teal(asa_pieces_total, asa_pieces_id,
                                      dealer['pk'], opponent['pk'])
    asc1_sink_compiled = algod_client.compile(asc1_sink_source)

    sink_lsig = transaction.LogicSig(
        base64.decodebytes(asc1_sink_compiled['result'].encode()))
    addr_sink = asc1_sink_compiled['hash']

    # Initialize AlgoNim ASC1 Sink Account with ALGO
    print("")
    print("Initializing Sink Account...")
    send(algod_client, dealer, addr_sink, 300000)

    # AlgoNim ASC1 Sink Account Opt-In
    print("")
    print("Sink Account AlgoNim ASA Piece Opt-In...")
    sink_opt_in_txn = unsigned_asset_send(algod_client, addr_sink, addr_sink,
                                          asa_pieces_id, 0)
    sink_opt_in_lstxn = transaction.LogicSigTransaction(
        sink_opt_in_txn, sink_lsig)
    txid = algod_client.send_transactions([sink_opt_in_lstxn])
    print("Transaction ID:", txid)
    wait_for_tx_confirmation(algod_client, txid)

    # TEAL: AlgoNim ASC1 Game Table
    print("")
    print("Dealer writing AlgoNim ASC1 Game Table TEAL for this match...")
    asc1_game_table_source = asc1_game_table_teal(asa_pieces_total,
                                                  asa_pieces_id,
                                                  asa_pieces_max_remove,
                                                  asa_turn_id, dealer['pk'],
                                                  opponent['pk'], addr_sink)
    asc1_game_table_compiled = algod_client.compile(asc1_game_table_source)

    game_table_lsig = transaction.LogicSig(
        base64.decodebytes(asc1_game_table_compiled['result'].encode()))
    addr_game_table = asc1_game_table_compiled['hash']

    # Initialize AlgoNim ASC1 Game Table Account with ALGO
    print("")
    print("Initializing Game Table Account...")
    send(algod_client, dealer, addr_game_table, 300000)

    # Dealer Sets Up the Game Table with AlgoNim ASA Pieces
    print("")
    print("Dealer distributing ASA Pieces on the Game Table...")
    gt_opt_in_txn = unsigned_asset_send(algod_client, addr_game_table,
                                        addr_game_table, asa_pieces_id, 0)
    deal_pieces_txn = unsigned_asset_send(algod_client, dealer['pk'],
                                          addr_game_table, asa_pieces_id,
                                          asa_pieces_total)

    # Dealer Gorup Transaction
    dealer_gid = transaction.calculate_group_id(
        [gt_opt_in_txn, deal_pieces_txn])
    gt_opt_in_txn.group = dealer_gid
    deal_pieces_txn.group = dealer_gid
    gt_opt_in_lstxn = transaction.LogicSigTransaction(gt_opt_in_txn,
                                                      game_table_lsig)
    deal_pieces_stxn = deal_pieces_txn.sign(dealer['sk'])
    dealer_sgtxn = [gt_opt_in_lstxn, deal_pieces_stxn]
    txid = algod_client.send_transactions(dealer_sgtxn)
    print("Transaction ID: ", txid)
    wait_for_tx_confirmation(algod_client, txid)

    # TEAL: AlgoNim ASC1 Bet Escrow
    print("")
    print("Dealer writing AlgoNim ASC1 Bet Escrow TEAL for Palyer 1...")
    asc1_dealer_bet_escrow_source, dealer_bet_escrow_expiry_block = asc1_bet_escrow_teal(
        algod_client, asa_pieces_total, asa_pieces_id, asa_turn_id,
        dealer['pk'], opponent['pk'], addr_sink, addr_game_table,
        match_hours_timeout)
    asc1_dealer_bet_escrow_compiled = algod_client.compile(
        asc1_dealer_bet_escrow_source)

    dealer_bet_escrow_lsig = transaction.LogicSig(
        base64.decodebytes(asc1_dealer_bet_escrow_compiled['result'].encode()))
    addr_dealer_bet_escrow = asc1_dealer_bet_escrow_compiled['hash']

    print("")
    print("Dealer writing AlgoNim ASC1 Bet Escrow TEAL for Palyer 2...")
    asc1_opponent_bet_escrow_source, opponent_bet_escrow_expiry_block = asc1_bet_escrow_teal(
        algod_client, asa_pieces_total, asa_pieces_id, asa_turn_id,
        opponent['pk'], dealer['pk'], addr_sink, addr_game_table,
        match_hours_timeout)
    asc1_opponent_bet_escrow_compiled = algod_client.compile(
        asc1_opponent_bet_escrow_source)

    opponent_bet_escrow_lsig = transaction.LogicSig(
        base64.decodebytes(
            asc1_opponent_bet_escrow_compiled['result'].encode()))
    addr_opponent_bet_escrow = asc1_opponent_bet_escrow_compiled['hash']

    # Initialize AlgoNim ASC1 Escrows with 0.1 ALGO
    print("")
    print("Initializing Bet Escrow Accounts...")
    send(algod_client, dealer, addr_dealer_bet_escrow, 100000)
    print("")
    send(algod_client, dealer, addr_opponent_bet_escrow, 100000)

    # Creating Bet Atomic Transfer to be signed by the Opponent
    dealer_bet_stxn, opponent_bet_txn = bet_atomic_transfer(
        algod_client, dealer, opponent['pk'], addr_dealer_bet_escrow,
        addr_opponent_bet_escrow, microalgo_bet_amount)

    match_data = {}
    match_data['dealer'] = dealer['pk']
    match_data['opponent'] = opponent['pk']
    match_data['asa_pieces_id'] = asa_pieces_id
    match_data['asa_pieces_max_remove'] = asa_pieces_max_remove
    match_data['asa_turn_id'] = asa_turn_id
    match_data['sink'] = addr_sink
    match_data['sink_lsig'] = encoding.msgpack_encode(sink_lsig)
    match_data['game_table'] = addr_game_table
    match_data['game_table_lsig'] = encoding.msgpack_encode(game_table_lsig)
    match_data['dealer_bet_escrow'] = addr_dealer_bet_escrow
    match_data['dealer_bet_escrow_lsig'] = encoding.msgpack_encode(
        dealer_bet_escrow_lsig)
    match_data['opponent_bet_escrow'] = addr_opponent_bet_escrow
    match_data['opponent_bet_escrow_lsig'] = encoding.msgpack_encode(
        opponent_bet_escrow_lsig)
    match_data['dealer_bet_stxn'] = encoding.msgpack_encode(dealer_bet_stxn)
    match_data['opponent_bet_txn'] = encoding.msgpack_encode(opponent_bet_txn)
    match_data['microalgo_bet_amount'] = microalgo_bet_amount
    match_data['match_hours_timeout'] = match_hours_timeout
    match_data['dealer_bet_escrow_expiry'] = dealer_bet_escrow_expiry_block
    match_data['opponent_bet_escrow_expiry'] = opponent_bet_escrow_expiry_block
    match_data_bytes = msgpack.packb(match_data)
    match_data_fname = 'algonim.match'

    with open(match_data_fname, "wb") as f:
        f.write(match_data_bytes)
        f.close()

    print("                                ")
    print("              _       _         ")
    print("  /\/\   __ _| |_ ___| |__    _ ")
    print(" /    \ / _` | __/ __| '_ \  (_)")
    print("/ /\/\ \ (_| | || (__| | | |  _ ")
    print("\/    \/\__,_|\__\___|_| |_| (_)")
    print("                                ")
    print("MATCH DURATION:\t\t", match_data['match_hours_timeout'] * 60, "min")
    print("PIECES ON GAME TABLE:\t", asa_pieces_total, "\n")
    print("RULES:")
    print("1. Players on each turn must remove at least 1 ASA Piece")
    print("2. Players on each turn must remove at most",
          match_data['asa_pieces_max_remove'], "ASA Piece")
    print("3. Who removes the last ASA Piece form the Game Table wins the " +
          "match!\n")
    print("Player 1 - Dealer:\t" + match_data['dealer'])
    print("Player 2 - Opponent:\t" + match_data['opponent'], "\n")
    print("AlgoNim ASA Pieces ID:\t", match_data['asa_pieces_id'])
    print("AlgoNim ASA Turn ID:\t", match_data['asa_turn_id'], "\n")
    print("AlgoNim Sink Account:\t\t\t" + match_data['sink'])
    print("AlgoNim Game Table Account:\t\t" + match_data['game_table'])
    print("AlgoNim Bet Escrow Player 1 Account:\t" +
          match_data['dealer_bet_escrow'])
    print("AlgoNim Bet Escrow Player 2 Account:\t" +
          match_data['opponent_bet_escrow'])
    print("\nSend 'algonim.match' file to your opponent join the match!\n")
    print("May the best win!\n")
Esempio n. 29
0
# get the mnemonic for address_1
mn = mnemonic.from_private_key(private_key_1)
print("Mnemonic for the first account: " + mn + "\n")

# get suggested parameters
sp = acl.suggested_params()

# get last block info
block_info = acl.block_info(sp.first)
print("Block", sp.first, "info:", json.dumps(block_info, indent=2), "\n")

# create a transaction
amount = 100000
txn = transaction.PaymentTxn(existing_account, sp, address_1, amount)
print("Encoded transaction:", encoding.msgpack_encode(txn), "\n")

# sign transaction with kmd
signed_with_kmd = kcl.sign_transaction(existing_handle, existing_wallet_pswd,
                                       txn)

# get the private key for the existing account
private_key = kcl.export_key(existing_handle, existing_wallet_pswd,
                             existing_account)

# sign transaction offline
signed_offline = txn.sign(private_key)
print("Signature: " + signed_offline.signature + "\n")

# check that they're the same
if signed_offline.dictify() == signed_with_kmd.dictify():
Esempio n. 30
0
    "Please go to: https://bank.testnet.algorand.network/ to fund your multisig account."
    + '\n' + "Press Enter to continue...")

# get suggested parameters
params = acl.suggested_params()
gen = params["genesisID"]
gh = params["genesishashb64"]
last_round = params["lastRound"]
fee = params["fee"]

# create a transaction
sender = msig.address()
recipient = "4CXXFP3SJJW63HGEQD4OPSDPPIYDW7BXCVP4DQZG7T33Z3BXTOA4UMEDM4"
amount = 10000
txn = transaction.PaymentTxn(sender, fee, last_round, last_round + 100, gh,
                             recipient, amount)

# create a SignedTransaction object
mtx = transaction.MultisigTransaction(txn, msig)

# sign the transaction
mtx.sign(private_key_1)
mtx.sign(private_key_2)

# print encoded transaction
print(encoding.msgpack_encode(mtx))

# send the transaction
transaction_id = acl.send_raw_transaction(encoding.msgpack_encode(mtx))
print("\nTransaction was sent!")
print("Transaction ID: " + transaction_id + "\n")