Skip to content

Instantly share code, notes, and snippets.

@letmejustputthishere
Forked from toysrtommy/neuron.py
Last active June 2, 2021 14:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save letmejustputthishere/b7bb633e43980e769732358b7bcc0a93 to your computer and use it in GitHub Desktop.
Save letmejustputthishere/b7bb633e43980e769732358b7bcc0a93 to your computer and use it in GitHub Desktop.
IC: Creating a new neuron (python)
from hashlib import sha224, sha256
import os
import base64
import zlib
import sys
CA_NNS = "rrkah-fqaaa-aaaaa-aaaaq-cai"
if len(sys.argv) < 2:
print("provide your principal as an argument!")
sys.exit()
principal = sys.argv[1]
# Generate subaccount based on principal
def nns_subaccount(principal_str):
nounce = os.urandom(8)
nounce_s = str(int.from_bytes(nounce, "big"))
# print(principal_str)
principal = principal_to_blob(principal_str)
padding = b'neuron-stake'
subaccount = sha256(b'\x0c' + padding + principal + nounce).hexdigest()
subaccount = bytearray.fromhex(subaccount)
# print("subaccount: " + bytes_to_string(subaccount))
nns_accountid = principal_to_accountid(principal_to_blob_str(CA_NNS),
subaccount)
checksum = hex(zlib.crc32(bytes.fromhex(nns_accountid)) & 0xffffffff)
nns_accountid = checksum + nns_accountid
return nns_accountid, nounce_s
def principal_to_blob_str(principal):
pid = principal_to_blob(principal)
p = "".join('{:02x}'.format(x) for x in pid)
return p
def principal_to_blob(principal):
principal = principal.replace("-", "")
# print("extra: " + str(len(str.encode(principal)) % 8))
# Pad as neccessary for base32 decoding
pad = 8 - len(str.encode(principal)) % 8
principal += "=" * pad
# print(principal)
principal = base64.b32decode(principal, True)
principal = principal[4:len(principal)]
p = "".join('{:02d} '.format(x) for x in principal)
# print("blob: " + p)
return principal
def principal_to_accountid(principal, subaccount=None):
# print("decoding principal ... " + principal)
p = bytes.fromhex(principal)
pad = subaccount
# print("decimal subaccount array (%s): " % len(subaccount) + bytes_to_string(subaccount) )
if (not subaccount):
pad = b'\x00' * 32
s = sha224(b'\x0aaccount-id' + p + pad)
return s.hexdigest()
# Generate a neuron account id (a subaccount of governance canister)
dest, memo = nns_subaccount(principal)
print("address: \n" + dest[2:])
print("memo: \n" + memo)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment