Example #1
0
 def send_create_account_tx(self, new_account_id, base_block_hash=None):
     self.prep_tx()
     new_key = Key(new_account_id, self.key.pk, self.key.sk)
     tx = sign_create_account_with_full_access_key_and_balance_tx(
         self.key, new_account_id, new_key, 100 * NEAR_BASE, self.nonce,
         base_block_hash or self.base_block_hash)
     return self.send_tx(tx)
def create_account(source_account, base_block_hash):
    nonce = get_nonce_for_pk(source_account.account_id, source_account.pk)
    new_account_id = ''.join(
        random.choice(string.ascii_lowercase) for _ in range(0, 10))
    new_key = Key(new_account_id, source_account.pk, source_account.sk)
    tx = sign_create_account_with_full_access_key_and_balance_tx(
        source_account, new_account_id, new_key, 100, nonce + 1,
        base_block_hash)
    send_tx(tx)
Example #3
0
 def create_account(self, user, node):
     status = node.get_status(check_storage=False)
     h = base58.b58decode(
         status['sync_info']['latest_block_hash'].encode('utf8'))
     nonce = node.get_nonce_for_pk(node.signer_key.account_id,
                                   node.signer_key.pk)
     create_account_tx = sign_create_account_with_full_access_key_and_balance_tx(
         node.signer_key, user.near_account_name, user.near_signer_key,
         billion_tokens // 10, nonce + 1, h)
     res = node.send_tx(create_account_tx)['result']
     while True:
         try:
             created = node.get_tx(res, user.near_account_name)
             if 'status' in created['result']:
                 # tx is accepted by network
                 break
         except:
             time.sleep(1)
     # check the result of tx execution
     assert_success(created['result']['status']['SuccessValue'])
Example #4
0
time.sleep(2)
nodes[1].kill()
print('node1 is killed')

status = nodes[0].get_status()
block_hash = status['sync_info']['latest_block_hash']
cur_height = status['sync_info']['latest_block_height']

num_new_accounts = 10
balance = 50000000000000000000000000000000
account_keys = []
for i in range(num_new_accounts):
    signer_key = Key(f'test_account{i}', nodes[0].signer_key.pk,
                     nodes[0].signer_key.sk)
    create_account_tx = sign_create_account_with_full_access_key_and_balance_tx(
        nodes[0].signer_key, f'test_account{i}', signer_key,
        balance // num_new_accounts, i + 1,
        base58.b58decode(block_hash.encode('utf8')))
    account_keys.append(signer_key)
    res = nodes[0].send_tx_and_wait(create_account_tx, timeout=15)
    assert 'error' not in res, res

target_height = 50
while cur_height < target_height:
    status = nodes[0].get_status()
    cur_height = status['sync_info']['latest_block_height']
    time.sleep(1)

status = nodes[0].get_status()
block_hash = status['sync_info']['latest_block_hash']

for signer_key in account_keys:
Example #5
0
def main():
    node_root = utils.get_near_tempdir('backward', clean=True)
    executables = branches.prepare_ab_test()

    # Setup local network.
    subprocess.check_call([
        executables.stable.neard,
        "--home=%s" % node_root,
        # TODO(#4372): testnet subcommand deprecated since 1.24.  Replace with
        # localnet after a couple of releases in 2022.
        "testnet",
        "--v",
        "2",
        "--prefix",
        "test"
    ])

    # Run both binaries at the same time.
    config = executables.stable.node_config()
    stable_node = cluster.spin_up_node(config, executables.stable.root,
                                       str(node_root / 'test0'), 0)
    config = executables.current.node_config()
    current_node = cluster.spin_up_node(config,
                                        executables.current.root,
                                        str(node_root / 'test1'),
                                        1,
                                        boot_node=stable_node)

    # Check it all works.
    BLOCKS = 100
    max_height = -1
    started = time.time()

    # Create account, transfer tokens, deploy contract, invoke function call
    block_hash = stable_node.get_latest_block().hash_bytes

    new_account_id = 'test_account.test0'
    new_signer_key = cluster.Key(new_account_id, stable_node.signer_key.pk,
                                 stable_node.signer_key.sk)
    create_account_tx = sign_create_account_with_full_access_key_and_balance_tx(
        stable_node.signer_key, new_account_id, new_signer_key, 10**24, 1,
        block_hash)
    res = stable_node.send_tx_and_wait(create_account_tx, timeout=20)
    assert 'error' not in res, res
    assert 'Failure' not in res['result']['status'], res

    transfer_tx = sign_payment_tx(stable_node.signer_key, new_account_id,
                                  10**25, 2, block_hash)
    res = stable_node.send_tx_and_wait(transfer_tx, timeout=20)
    assert 'error' not in res, res

    block_height = stable_node.get_latest_block().height
    nonce = block_height * 1_000_000 - 1

    tx = sign_deploy_contract_tx(new_signer_key, utils.load_test_contract(),
                                 nonce, block_hash)
    res = stable_node.send_tx_and_wait(tx, timeout=20)
    assert 'error' not in res, res

    tx = sign_deploy_contract_tx(stable_node.signer_key,
                                 utils.load_test_contract(), 3, block_hash)
    res = stable_node.send_tx_and_wait(tx, timeout=20)
    assert 'error' not in res, res

    tx = sign_function_call_tx(new_signer_key, new_account_id,
                               'write_random_value', [], 10**13, 0, nonce + 1,
                               block_hash)
    res = stable_node.send_tx_and_wait(tx, timeout=20)
    assert 'error' not in res, res
    assert 'Failure' not in res['result']['status'], res

    data = json.dumps([{
        "create": {
            "account_id": "test_account.test0",
            "method_name": "call_promise",
            "arguments": [],
            "amount": "0",
            "gas": 30000000000000,
        },
        "id": 0
    }, {
        "then": {
            "promise_index": 0,
            "account_id": "test0",
            "method_name": "call_promise",
            "arguments": [],
            "amount": "0",
            "gas": 30000000000000,
        },
        "id": 1
    }])

    tx = sign_function_call_tx(stable_node.signer_key,
                               new_account_id, 'call_promise',
                               bytes(data, 'utf-8'), 90000000000000, 0,
                               nonce + 2, block_hash)
    res = stable_node.send_tx_and_wait(tx, timeout=20)

    assert 'error' not in res, res
    assert 'Failure' not in res['result']['status'], res

    utils.wait_for_blocks(current_node, target=BLOCKS)
Example #6
0
def test_changes_with_new_account_with_access_key():
    """
    Plan:
    1. Create a new account with an access key.
    2. Observe the changes in the block where the receipt lands.
    3. Remove the access key.
    4. Observe the changes in the block where the receipt lands.
    """

    # re-use the key as a new account access key
    new_key = Key(
        account_id='rpc_key_value_changes_full_access',
        pk=nodes[1].signer_key.pk,
        sk=nodes[1].signer_key.sk,
    )

    # Step 1
    status = nodes[0].get_status()
    latest_block_hash = status['sync_info']['latest_block_hash']
    create_account_tx = transaction.sign_create_account_with_full_access_key_and_balance_tx(
        creator_key=nodes[0].signer_key,
        new_account_id=new_key.account_id,
        new_key=new_key,
        balance=10**24,
        nonce=7,
        block_hash=base58.b58decode(latest_block_hash.encode('utf8')))
    new_account_response = nodes[0].send_tx_and_wait(create_account_tx, 10)

    # Step 2
    block_hash = new_account_response['result']['receipts_outcome'][0][
        'block_hash']
    assert_changes_in_block_response(request={"block_id": block_hash},
                                     expected_response={
                                         "block_hash":
                                         block_hash,
                                         "changes": [{
                                             "type":
                                             "account_touched",
                                             "account_id":
                                             new_key.account_id,
                                         }, {
                                             "type":
                                             "access_key_touched",
                                             "account_id":
                                             new_key.account_id,
                                         }]
                                     })

    base_request = {
        "block_id": block_hash,
        "changes_type": "all_access_key_changes",
    }
    for request in [
            # Test empty account_ids
        {
            **base_request, "account_ids": []
        },
            # Test an account_id that is a prefix of the original account_id.
        {
            **base_request, "account_ids": [new_key.account_id[:-1]]
        },
            # Test an account_id that has the original account_id as a prefix.
        {
            **base_request, "account_ids": [new_key.account_id + '_extra']
        },
    ]:
        assert_changes_response(request=request,
                                expected_response={
                                    "block_hash": block_hash,
                                    "changes": []
                                })

    # Test happy-path
    expected_response = {
        "block_hash":
        block_hash,
        "changes": [{
            "cause": {
                "type":
                "receipt_processing",
                "receipt_hash":
                new_account_response["result"]["receipts_outcome"][0]["id"],
            },
            "type": "access_key_update",
            "change": {
                "account_id": new_key.account_id,
                "public_key": new_key.pk,
                "access_key": {
                    "nonce": 0,
                    "permission": "FullAccess"
                },
            }
        }]
    }
    for request in [
        {
            "block_id": block_hash,
            "changes_type": "all_access_key_changes",
            "account_ids": [new_key.account_id],
        },
        {
            "block_id":
            block_hash,
            "changes_type":
            "all_access_key_changes",
            "account_ids": [
                new_key.account_id + '_non_existing1', new_key.account_id,
                new_key.account_id + '_non_existing2'
            ],
        },
    ]:
        assert_changes_response(request=request,
                                expected_response=expected_response)

    # Step 3
    status = nodes[0].get_status()
    latest_block_hash = status['sync_info']['latest_block_hash']
    delete_access_key_tx = transaction.sign_delete_access_key_tx(
        signer_key=new_key,
        target_account_id=new_key.account_id,
        key_for_deletion=new_key,
        nonce=8,
        block_hash=base58.b58decode(latest_block_hash.encode('utf8')))
    delete_access_key_response = nodes[1].send_tx_and_wait(
        delete_access_key_tx, 10)

    # Step 4
    block_hash = delete_access_key_response['result']['receipts_outcome'][0][
        'block_hash']
    assert_changes_in_block_response(request={"block_id": block_hash},
                                     expected_response={
                                         "block_hash":
                                         block_hash,
                                         "changes": [{
                                             "type":
                                             "account_touched",
                                             "account_id":
                                             new_key.account_id,
                                         }, {
                                             "type":
                                             "access_key_touched",
                                             "account_id":
                                             new_key.account_id,
                                         }]
                                     })

    base_request = {
        "block_id": block_hash,
        "changes_type": "all_access_key_changes",
    }
    for request in [
            # Test empty account_ids
        {
            **base_request, "account_ids": []
        },
            # Test an account_id that is a prefix of the original account_id
        {
            **base_request, "account_ids": [new_key.account_id[:-1]]
        },
            # Test an account_id that has the original account_id as a prefix
        {
            **base_request, "account_ids": [new_key.account_id + '_extra']
        },
            # Test empty keys in single_access_key_changes request
        {
            "block_id": block_hash,
            "changes_type": "single_access_key_changes",
            "keys": []
        },
            # Test non-existing account_id
        {
            "block_id":
            block_hash,
            "changes_type":
            "single_access_key_changes",
            "keys": [
                {
                    "account_id": new_key.account_id + '_non_existing1',
                    "public_key": new_key.pk
                },
            ],
        },
            # Test non-existing public_key for an existing account_id
        {
            "block_id":
            block_hash,
            "changes_type":
            "single_access_key_changes",
            "keys": [
                {
                    "account_id": new_key.account_id,
                    "public_key": new_key.pk[:-3] + 'aaa'
                },
            ],
        },
    ]:
        assert_changes_response(request=request,
                                expected_response={
                                    "block_hash": block_hash,
                                    "changes": []
                                })

    # Test happy-path
    expected_response = {
        "block_hash":
        block_hash,
        "changes": [{
            "cause": {
                'type':
                'transaction_processing',
                'tx_hash':
                delete_access_key_response['result']['transaction']['hash'],
            },
            "type": "access_key_update",
            "change": {
                "account_id": new_key.account_id,
                "public_key": new_key.pk,
                "access_key": {
                    "nonce": 8,
                    "permission": "FullAccess"
                },
            }
        }, {
            "cause": {
                "type":
                "receipt_processing",
                "receipt_hash":
                delete_access_key_response["result"]["receipts_outcome"][0]
                ["id"]
            },
            "type": "access_key_deletion",
            "change": {
                "account_id": new_key.account_id,
                "public_key": new_key.pk,
            }
        }]
    }

    for request in [
        {
            "block_id": block_hash,
            "changes_type": "all_access_key_changes",
            "account_ids": [new_key.account_id],
        },
        {
            "block_id":
            block_hash,
            "changes_type":
            "all_access_key_changes",
            "account_ids": [
                new_key.account_id + '_non_existing1', new_key.account_id,
                new_key.account_id + '_non_existing2'
            ],
        },
        {
            "block_id": block_hash,
            "changes_type": "single_access_key_changes",
            "keys": [{
                "account_id": new_key.account_id,
                "public_key": new_key.pk
            }],
        },
        {
            "block_id":
            block_hash,
            "changes_type":
            "single_access_key_changes",
            "keys": [
                {
                    "account_id": new_key.account_id + '_non_existing1',
                    "public_key": new_key.pk
                },
                {
                    "account_id": new_key.account_id,
                    "public_key": new_key.pk
                },
            ],
        },
    ]:
        assert_changes_response(request=request,
                                expected_response=expected_response)
Example #7
0
def main():
    node_root = "/tmp/near/upgradable"
    if os.path.exists(node_root):
        shutil.rmtree(node_root)
    subprocess.check_output('mkdir -p /tmp/near', shell=True)

    branch = branches.latest_rc_branch()
    print(f"Latest rc release branch is {branch}")
    near_root, (stable_branch,
                current_branch) = branches.prepare_ab_test(branch)

    # Setup local network.
    print([
        "%snear-%s" % (near_root, stable_branch),
        "--home=%s" % node_root, "testnet", "--v", "4", "--prefix", "test"
    ])
    subprocess.call([
        "%snear-%s" % (near_root, stable_branch),
        "--home=%s" % node_root, "testnet", "--v", "4", "--prefix", "test"
    ])
    genesis_config_changes = [("epoch_length", 20),
                              ("num_block_producer_seats", 10),
                              ("num_block_producer_seats_per_shard", [10]),
                              ("block_producer_kickout_threshold", 80),
                              ("chunk_producer_kickout_threshold", 80),
                              ("chain_id", "testnet")]
    node_dirs = [os.path.join(node_root, 'test%d' % i) for i in range(4)]
    for i, node_dir in enumerate(node_dirs):
        cluster.apply_genesis_changes(node_dir, genesis_config_changes)

    # Start 3 stable nodes and one current node.
    config = {
        "local": True,
        'near_root': near_root,
        'binary_name': "near-%s" % stable_branch
    }
    nodes = [
        cluster.spin_up_node(config, near_root, node_dirs[0], 0, None, None)
    ]
    for i in range(1, 3):
        nodes.append(
            cluster.spin_up_node(config, near_root, node_dirs[i], i,
                                 nodes[0].node_key.pk, nodes[0].addr()))
    if os.getenv('NAYDUCK'):
        config["binary_name"] = "near"
    else:
        config["binary_name"] = "near-%s" % current_branch
    nodes.append(
        cluster.spin_up_node(config, near_root, node_dirs[3], 3,
                             nodes[0].node_key.pk, nodes[0].addr()))

    time.sleep(2)

    # deploy a contract
    status = nodes[0].get_status()
    hash = status['sync_info']['latest_block_hash']
    tx = sign_deploy_contract_tx(
        nodes[0].signer_key,
        load_binary_file(
            '../runtime/near-test-contracts/res/test_contract_rs.wasm'), 1,
        base58.b58decode(hash.encode('utf8')))
    res = nodes[0].send_tx_and_wait(tx, timeout=20)
    assert 'error' not in res, res

    # write some random value
    tx = sign_function_call_tx(nodes[0].signer_key,
                               nodes[0].signer_key.account_id,
                               'write_random_value', [], 10**13, 0, 2,
                               base58.b58decode(hash.encode('utf8')))
    res = nodes[0].send_tx_and_wait(tx, timeout=20)
    assert 'error' not in res, res
    assert 'Failure' not in res['result']['status'], res

    wait_for_blocks_or_timeout(nodes[0], 20, 120)

    # Restart stable nodes into new version.
    for i in range(3):
        nodes[i].kill()
        nodes[i].binary_name = config['binary_name']
        nodes[i].start(nodes[0].node_key.pk, nodes[0].addr())

    wait_for_blocks_or_timeout(nodes[3], 60, 120)
    status0 = nodes[0].get_status()
    status3 = nodes[3].get_status()
    protocol_version = status0['protocol_version']
    latest_protocol_version = status3["latest_protocol_version"]
    assert protocol_version == latest_protocol_version, \
        "Latest protocol version %d should match active protocol version %d" % (
        latest_protocol_version, protocol_version)

    hash = status0['sync_info']['latest_block_hash']

    # write some random value again
    tx = sign_function_call_tx(nodes[0].signer_key,
                               nodes[0].signer_key.account_id,
                               'write_random_value', [], 10**13, 0, 4,
                               base58.b58decode(hash.encode('utf8')))
    res = nodes[0].send_tx_and_wait(tx, timeout=20)
    assert 'error' not in res, res
    assert 'Failure' not in res['result']['status'], res

    # hex_account_id = (b"I'm hex!" * 4).hex()
    hex_account_id = '49276d206865782149276d206865782149276d206865782149276d2068657821'
    tx = sign_payment_tx(key=nodes[0].signer_key,
                         to=hex_account_id,
                         amount=10**25,
                         nonce=5,
                         blockHash=base58.b58decode(hash.encode('utf8')))
    res = nodes[0].send_tx_and_wait(tx, timeout=20)
    # Successfully created a new account on transfer to hex
    assert 'error' not in res, res
    assert 'Failure' not in res['result']['status'], res

    hex_account_balance = int(
        nodes[0].get_account(hex_account_id)['result']['amount'])
    assert hex_account_balance == 10**25

    hash = status0['sync_info']['latest_block_hash']

    new_account_id = f'new.{nodes[0].signer_key.account_id}'
    new_signer_key = cluster.Key(new_account_id, nodes[0].signer_key.pk,
                                 nodes[0].signer_key.sk)
    create_account_tx = sign_create_account_with_full_access_key_and_balance_tx(
        nodes[0].signer_key, new_account_id, new_signer_key, 10**24, 6,
        base58.b58decode(hash.encode('utf8')))
    res = nodes[0].send_tx_and_wait(create_account_tx, timeout=20)
    # Successfully created a new account
    assert 'error' not in res, res
    assert 'Failure' not in res['result']['status'], res

    hash = status0['sync_info']['latest_block_hash']

    status = nodes[0].get_status()
    block_height = status['sync_info']['latest_block_height']
    beneficiary_account_id = '1982374698376abd09265034ef35034756298375462323456294875193563756'
    tx = sign_delete_account_tx(key=new_signer_key,
                                to=new_account_id,
                                beneficiary=beneficiary_account_id,
                                nonce=block_height * 1_000_000 - 1,
                                block_hash=base58.b58decode(
                                    hash.encode('utf8')))
    res = nodes[0].send_tx_and_wait(tx, timeout=20)
    # Successfully deleted an account
    assert 'error' not in res, res
    assert 'Failure' not in res['result']['status'], res
Example #8
0
def main():
    node_root = "/tmp/near/backward"
    if os.path.exists(node_root):
        shutil.rmtree(node_root)
    subprocess.check_output('mkdir -p /tmp/near', shell=True)

    branch = branches.latest_rc_branch()
    near_root, (stable_branch,
                current_branch) = branches.prepare_ab_test(branch)

    # Setup local network.
    subprocess.call([
        "%snear-%s" % (near_root, stable_branch),
        "--home=%s" % node_root, "testnet", "--v", "2", "--prefix", "test"
    ])

    # Run both binaries at the same time.
    config = {
        "local": True,
        'near_root': near_root,
        'binary_name': "near-%s" % stable_branch
    }
    stable_node = cluster.spin_up_node(config, near_root,
                                       os.path.join(node_root, "test0"), 0,
                                       None, None)
    config["binary_name"] = "near-%s" % current_branch
    current_node = cluster.spin_up_node(config, near_root,
                                        os.path.join(node_root, "test1"), 1,
                                        stable_node.node_key.pk,
                                        stable_node.addr())

    # Check it all works.
    BLOCKS = 100
    TIMEOUT = 150
    max_height = -1
    started = time.time()

    # Create account, transfer tokens, deploy contract, invoke function call
    status = stable_node.get_status()
    block_hash = base58.b58decode(
        status['sync_info']['latest_block_hash'].encode('utf-8'))

    new_account_id = 'test_account'
    new_signer_key = cluster.Key(new_account_id, stable_node.signer_key.pk,
                                 stable_node.signer_key.sk)
    create_account_tx = sign_create_account_with_full_access_key_and_balance_tx(
        stable_node.signer_key, new_account_id, new_signer_key, 10**24, 1,
        block_hash)
    res = stable_node.send_tx_and_wait(create_account_tx, timeout=20)
    assert 'error' not in res, res
    assert 'Failure' not in res['result']['status'], res

    transfer_tx = sign_payment_tx(stable_node.signer_key, new_account_id,
                                  10**25, 2, block_hash)
    res = stable_node.send_tx_and_wait(transfer_tx, timeout=20)
    assert 'error' not in res, res

    status = stable_node.get_status()
    block_height = status['sync_info']['latest_block_height']
    nonce = block_height * 1_000_000 - 1

    tx = sign_deploy_contract_tx(new_signer_key, load_test_contract(), nonce,
                                 block_hash)
    res = stable_node.send_tx_and_wait(tx, timeout=20)
    assert 'error' not in res, res

    tx = sign_function_call_tx(new_signer_key, new_account_id,
                               'write_random_value', [], 10**13, 0, nonce + 1,
                               block_hash)
    res = stable_node.send_tx_and_wait(tx, timeout=20)
    assert 'error' not in res, res
    assert 'Failure' not in res['result']['status'], res

    data = json.dumps([{
        "create": {
            "account_id": "near_2",
            "method_name": "call_promise",
            "arguments": [],
            "amount": "0",
            "gas": 30000000000000,
        },
        "id": 0
    }, {
        "then": {
            "promise_index": 0,
            "account_id": "near_3",
            "method_name": "call_promise",
            "arguments": [],
            "amount": "0",
            "gas": 30000000000000,
        },
        "id": 1
    }])

    tx = sign_function_call_tx(new_signer_key, new_account_id, 'call_promise',
                               bytes(data, 'utf-8'), 90000000000000, 0,
                               nonce + 2, block_hash)
    res = stable_node.send_tx_and_wait(tx, timeout=20)

    assert 'error' not in res, res
    assert 'Failure' not in res['result']['status'], res

    while max_height < BLOCKS:
        assert time.time() - started < TIMEOUT
        status = current_node.get_status()
        cur_height = status['sync_info']['latest_block_height']

        if cur_height > max_height:
            max_height = cur_height
        time.sleep(1)
Example #9
0
     ["chunk_producer_kickout_threshold", 10]], {1: node1_config})
time.sleep(2)
nodes[1].kill()
logger.info('node1 is killed')

block_hash = nodes[0].get_latest_block().hash_bytes

num_new_accounts = 10
balance = 50000000000000000000000000000000
account_keys = []
for i in range(num_new_accounts):
    account_name = f'test_account{i}.test0'
    signer_key = Key(account_name, nodes[0].signer_key.pk,
                     nodes[0].signer_key.sk)
    create_account_tx = sign_create_account_with_full_access_key_and_balance_tx(
        nodes[0].signer_key, account_name, signer_key,
        balance // num_new_accounts, i + 1, block_hash)
    account_keys.append(signer_key)
    res = nodes[0].send_tx_and_wait(create_account_tx, timeout=15)
    assert 'error' not in res, res

latest_block = utils.wait_for_blocks(nodes[0], target=50)
cur_height = latest_block.height
block_hash = latest_block.hash_bytes

for signer_key in account_keys:
    staking_tx = sign_staking_tx(signer_key, nodes[0].validator_key,
                                 balance // (num_new_accounts * 2),
                                 cur_height * 1_000_000 - 1, block_hash)
    res = nodes[0].send_tx_and_wait(staking_tx, timeout=15)
    assert 'error' not in res