I'm trying to execute "transfer" function of an ERC-20 token with my ESP8266 Microcontroller using Micropython. The problem is Micropython doesn't have libraries like web3.py so i have to call raw JSON-RPC API on my own handling all the signature procedure on my own which is currently too much for me. Is there a way i can achieve it or if it's a microcontroller issue suggest a microcontroller which doesn't have this issue.
Here's my smart contract
pragma solidity ^0.4.24;
//Safe Math Interface
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) public pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint a, uint b) public pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
//ERC Token Standard #20 Interface
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
//Contract function to receive approval and execute function in one call
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
//Actual token contract
contract QKCToken is ERC20Interface, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
constructor() public {
symbol = "SWC";
name = "Swach Coin";
decimals = 2;
_totalSupply = 100000;
balances[0x7c26d596578bbDf17823efbE1F8c61a52b433898] = _totalSupply;
emit Transfer(address(0), 0x7c26d596578bbDf17823efbE1F8c61a52b433898, _totalSupply);
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
}
Here's what i tried though it didn't work. I tried coding the whole signature algo but yaa thats dumb
import json as json
import time
import urequests as requests
import network
import hashlib
import random
import urandom
def randint(min, max):
print(max,min)
span = max - min + 1
div = 0x3fffffff // span
offset = (urandom.getrandbits(30) // div)+1
val = min + offset
return val
class Point:
def __init__(self, x, y, curve):
self.x = x
self.y = y
self.curve = curve
def __add__(self, other):
if self.curve != other.curve:
raise ValueError("Points not on the same curve")
if self == other:
return self.double()
if self.x == other.x:
return self.curve.zero
m = (self.y - other.y) * inverse_mod(self.x - other.x, self.curve.p)
x = (m * m - self.x - other.x) % self.curve.p
y = (m * (self.x - x) - self.y) % self.curve.p
return Point(x, y, self.curve)
def __rmul__(self, k):
n = self.curve.n
if n is None:
raise ValueError("Curve does not have order")
e = k % n
if e == 0 or self == self.curve.zero:
return self.curve.zero
e3 = 3 * e
neg_self = Point(self.x, -self.y, self.curve)
i = 1 << (e3.bit_length() - 1)
result = self
while i > 1:
result = result.double()
if e3 & i and not e & i:
result = result + self
if not e3 & i and e & i:
result = result + neg_self
i >>= 1
return result
def double(self):
if self == self.curve.zero:
return self.curve.zero
a = self.curve.a
p = self.curve.p
m = (3 * self.x * self.x + a) * inverse_mod(2 * self.y, p)
x = (m * m - 2 * self.x) % p
y = (m * (self.x - x) - self.y) % p
return Point(x, y, self.curve)
def __eq__(self, other):
if self.curve == other.curve:
return self.x == other.x and self.y == other.y
return False
class Curve:
def __init__(self, name, p, a, b, g, n, h):
self.name = name
self.p = p
self.a = a
self.b = b
self.g = g
self.n = n
self.h = h
self.zero = Point(None, None, self)
def __str__(self):
return self.name
# Utility functions
def inverse_mod(a, p):
if a == 0:
raise ZeroDivisionError("division by zero")
if a < 0:
return p - inverse_mod(-a, p)
s, old_s = 0, 1
t, old_t = 1, 0
r, old_r = p, a
while r != 0:
quotient = old_r // r
old_r, r = r, old_r - quotient * r
old_s, s = s, old_s - quotient * s
old_t, t = t, old_t - quotient * t
gcd, x, y = old_r, old_s, old_t
return x % p
# Define the curve
curve = Curve(
name="secp256k1",
p=0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F,
a=0,
b=7,
g=Point(
0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798,
0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8,
None
),
n=0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141,
h=1
)
def ecdsa_sign(message, private_key):
z = int.from_bytes(message, 'big')
r, s = 0, 0
while not r or not s:
k = randint(1, curve.n - 1)
p = k * curve.g
r = p.x % curve.n
s = ((z + r * private_key) * inverse_mod(k, curve.n)) % curve.n
return (r, s)
def ecdsa_verify(public_key, message, signature):
z = int.from_bytes(message, 'big')
r, s = signature
w = inverse_mod(s, curve.n)
u1 = (z * w) % curve.n
u2 = (r * w) % curve.n
p = u1 * curve.g + u2 * public_key
return p.x % curve.n == r
def private_key_to_public_key(private_key):
return private_key * curve.g
def keccak256(data):
keccak = hashlib.sha256()
keccak.update(data)
return keccak.digest()
# Construct and sign the transaction
def construct_raw_tx(nonce, gas_price, gas_limit, to, value, data, chain_id=1):
tx = {
'nonce': nonce,
'gasPrice': gas_price,
'gasLimit': gas_limit,
'to': to,
'value': value,
'data': data,
'v': chain_id,
'r': 0,
's': 0
}
return tx
def rlp_encode(item):
if isinstance(item, int):
if item == 0:
return b'\x80'
elif item < 128:
return bytes([item])
else:
hex_item = hex(item)[2:]
if len(hex_item) % 2:
hex_item = '0' + hex_item
item_bytes = bytes.fromhex(hex_item)
return bytes([len(item_bytes) + 0x80]) + item_bytes
elif isinstance(item, bytes):
if len(item) == 1 and item[0] < 128:
return item
else:
return bytes([len(item) + 0x80]) + item
elif isinstance(item, list):
encoded_items = b''.join(rlp_encode(i) for i in item)
if len(encoded_items) < 56:
return bytes([len(encoded_items) + 0xc0]) + encoded_items
else:
length_hex = hex(len(encoded_items))[2:]
if len(length_hex) % 2:
length_hex = '0' + length_hex
length_bytes = bytes.fromhex(length_hex)
return bytes([len(length_bytes) + 0xf7]) + length_bytes + encoded_items
else:
raise TypeError("Invalid type for RLP encoding")
# Test RLP encoding
tx = [
0x01, # nonce
0x09184e72a000, # gasPrice
0x2710, # gasLimit
bytes.fromhex("095e7baea6a6c7c4c2dfeb977efac326af552d87"), # to
0x00, # value
bytes.fromhex(""), # data
0x1c, # v
0x5e1d3a76fbf824220e00f44f, # r
0x29d5b6dbe0b6a3aef1b2c62c, # s
]
encoded_tx = rlp_encode(tx)
print(encoded_tx.hex())
def encode_tx(tx):
nonce_hex = zfill(hex(tx['nonce'])[2:], 64)
print(nonce_hex)
gas_price_hex = zfill(hex(tx['gasPrice'])[2:], 64)
gas_limit_hex = zfill(hex(tx['gasLimit'])[2:], 64)
to_hex = zfill(tx['to'][2:], 64)
value_hex = zfill(hex(tx['value'])[2:], 64)
data_hex = tx['data'][2:]
print(data_hex)
v_hex = zfill(hex(tx['v'])[2:], 2)
r_hex = zfill(hex(tx['r'])[2:], 64)
s_hex = zfill(hex(tx['s'])[2:], 64)
return rlp_encode([
int(nonce_hex, 16),
int(gas_price_hex, 16),
int(gas_limit_hex, 16),
bytes.fromhex(to_hex),
int(value_hex, 16),
bytes.fromhex(data_hex),
int(v_hex, 16),
int(r_hex, 16),
int(s_hex, 16),
])
def sign_tx(tx, private_key):
print("hello")
raw_tx = encode_tx(tx)
print("hello")
tx_hash = keccak256(raw_tx)
print("hello")
signature = ecdsa_sign(tx_hash, private_key)
print("hello")
r, s = signature
return r, s, tx_hash
def construct_signed_tx(tx, r, s, tx_hash, chain_id=1):
v = chain_id * 2 + 35
tx['v'] = v
tx['r'] = r
tx['s'] = s
return encode_tx(tx)
def zfill(s, width):
"""Pads the string `s` with zeros on the left, to fill the width specified by `width`."""
if len(s) >= width:
return s
return '0' * (width - len(s)) + s
ssid = 'Prem'
password = 'harsh123'
wlan = network.WLAN(network.STA_IF)
wlan.active(True) # Activate the interface
# Connect to the Wi-Fi network
wlan.connect(ssid, password)
# Wait for the connection to complete
while not wlan.isconnected():
print('Connecting to network...')
time.sleep(1)
print('Network connected!')
print('IP address:', wlan.ifconfig()[0])
with open('swach.json') as f:
abi = json.load(f)
# print("abi loaded")
infura_url ='https://sepolia.infura.io/v3/-------'
contract_address = '-----'
private_key = 'private key'
from_address = '-----'
to_address='------'
function_signature = '0xa9059cbb'
amount=5
recipient_address_padded = to_address
amount_padded = hex(amount)
data = '0xa9059cbbaddress0000000000000000000000000000000000000000000000000000000000000005'
payload_nonce = {
'jsonrpc': '2.0',
'method': 'eth_getTransactionCount',
'params': [from_address, 'latest'],
'id': 1
}
response_nonce = requests.post(infura_url, headers={'Content-Type': 'application/json'}, data=json.dumps(payload_nonce))
nonce = int(response_nonce.json()['result'], 16)
print(nonce)
# # Construct the transaction
tx = construct_raw_tx(nonce, 20000000000, 2000000, contract_address, 0, data)
# # Sign the transaction
r, s, tx_hash = sign_tx(tx, private_key)
signed_tx = construct_signed_tx(tx, r, s, tx_hash)
# # Send the signed transaction
# payload_send = {
# 'jsonrpc': '2.0',
# 'method': 'eth_sendRawTransaction',
# 'params': ['0x' + signed_tx.hex()],
# 'id': 1
# }
# response_send = requests.post(infura_url, headers={'Content-Type': 'application/json'}, data=json.dumps(payload_send))
# tx_hash = response_send.json()['result']
# print('Transaction Hash:', tx_hash)
A few points regarding your post, as I recently started a project that is an EVM wallet on MicroPython devices. What you did is both dumd and clever I would say. At least this is not efficient. And not secure, don't write your own security functions. I guess here the goal was to make it work.
First point is about the hash used in ECDSA. In your code you do:
keccak = hashlib.sha256()
which is not correct, it will SHA2 the transaction, and it shall be Keccak. And until recently there was no keccak available on MicroPython. I really cant find one, so I ended up doing it myself. I published an updated version of hashlib, this is the first block of the ChainSigner project. With that, that provides keccak256, and you can do hashlib.keccak256()
and that works as intended for web3 wallets.
For the remaining parts, you can use embit. It is designed for Bitcoin, but that performs ECDSA, BIP32/39,... Lots of useful things for a wallet. What remains is the Ethereum specific logic : Address computation, RLP, RPC, ... At least with embit, the core features of your wallet will be fast and secure.
For the RPC service, I appreciate using https://www.publicnode.com/. It is fast, free and reliable. They even provide WSS services (for free).