Skip to content

Instantly share code, notes, and snippets.

@rjl493456442
Created October 18, 2018 12:04
Show Gist options
  • Save rjl493456442/69b573c7a769b20bd5023e6a26b22ff2 to your computer and use it in GitHub Desktop.
Save rjl493456442/69b573c7a769b20bd5023e6a26b22ff2 to your computer and use it in GitHub Desktop.
transaction packing simulator
#!/usr/bin/python
# -*- coding: utf-8 -*-
import string
import random
import time
GAS_BLOCK_LIMIT = 8000000
GAS_UPPER_LIMIT = 300000
GAS_LOWER_LIMIT = 21000
GAS_PRICE_UPPER_LIMIT = 10 # 10GWei
GAS_PRICE_LOWER_LIMIT = 1 # 1GWei
def id_generator(size=40, chars=string.hexdigits):
return ''.join(random.choice(chars) for _ in range(size))
def init_txs(size=5):
txs = []
for nonce in range(size):
txs.append({"price": random.randint(GAS_PRICE_LOWER_LIMIT * 10, GAS_PRICE_UPPER_LIMIT * 10) / 10.0,
"gas": random.randint(GAS_LOWER_LIMIT, GAS_UPPER_LIMIT),
"nonce": nonce})
return txs
def init_pool(init_accounts=5):
accounts = []
for _ in range(init_accounts):
num = random.randint(0, 10)
accounts.append({"address": id_generator(),
"txs": init_txs(num),
"nonce": num})
return accounts
def new_txs(size, accounts):
for _ in range(size):
if bool(random.getrandbits(1)):
# generate a txs belongs to existing account
account = accounts[random.randint(0, len(accounts)-1)]
account["txs"].append({"price":random.randint(GAS_PRICE_LOWER_LIMIT, GAS_PRICE_UPPER_LIMIT),
"gas":random.randint(GAS_LOWER_LIMIT, GAS_UPPER_LIMIT),
"nonce": account["nonce"]})
account["nonce"] += 1
else:
# create a new account
accounts.append({"address": id_generator(),
"txs": init_txs(1),
"nonce": 1})
return accounts
def calculate(pool):
gasUsed = 0
reward = 0
counter = 0
for account in pool:
account["tmp"] = 0
while gasUsed <= GAS_BLOCK_LIMIT:
current = []
for idx, account in enumerate(pool):
if account["tmp"] == account["nonce"]:
continue
current.append((idx, account["txs"][account["tmp"]]))
if len(current) == 0:
break
current.sort(key=lambda x: x[1]["price"], reverse=True)
if gasUsed + current[0][1]["gas"] <= GAS_BLOCK_LIMIT:
gasUsed += current[0][1]["gas"]
counter += 1
reward += current[0][1]["gas"] * current[0][1]["price"]
# print "add", current[0][1]
pool[current[0][0]]["tmp"] += 1
return gasUsed, counter, reward
def simluate():
pool = init_pool(1)
gasUsed = 0
reward = 0
counter = 0
while True:
# insert 2 new txs
pool = new_txs(2, pool)
g, c, r = calculate(pool)
if r < reward:
print "=================================="
print "gasUsed", gasUsed, "tx number", counter, "total reward", reward
print "new gasUsed", g, "new tx number", c, "new total reward", r
gasUsed, counter, reward = g, c, r
if __name__ == "__main__":
simluate()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment