create-token.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2023 The MMGen Project <mmgen@tuta.io>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. import sys,os,json,re
  19. from subprocess import run,PIPE
  20. from collections import namedtuple
  21. from mmgen.common import *
  22. ti = namedtuple('token_param_info',['default','conversion','test'])
  23. class TokenData:
  24. fields = ('decimals','supply','name','symbol','owner_addr')
  25. decimals = ti('18', int, lambda s: s.isascii() and s.isdigit() and 0 < int(s) <= 36)
  26. name = ti(None, str, lambda s: s.isascii() and s.isprintable() and len(s) < 256)
  27. supply = ti(None, int, lambda s: s.isascii() and s.isdigit() and 0 < int(s) < 2**256)
  28. symbol = ti(None, str, lambda s: s.isascii() and s.isalnum() and len(s) <= 20)
  29. owner_addr = ti(None, str, lambda s: s.isascii() and s.isalnum() and len(s) == 40) # checked separately
  30. token_data = TokenData()
  31. req_solc_ver_pat = '^0.8.6'
  32. opts_data = {
  33. 'text': {
  34. 'desc': 'Create an ERC20 token contract',
  35. 'usage':'[opts] <owner address>',
  36. 'options': f"""
  37. -h, --help Print this help message
  38. -o, --outdir=D Specify output directory for *.bin files
  39. -d, --decimals=D Number of decimals for the token (default: {token_data.decimals.default})
  40. -n, --name=N Token name (REQUIRED)
  41. -p, --preprocess Print the preprocessed code to stdout
  42. -t, --supply=T Total supply of the token (REQUIRED)
  43. -s, --symbol=S Token symbol (REQUIRED)
  44. -S, --stdout Output JSON data to stdout instead of files
  45. -v, --verbose Produce more verbose output
  46. -c, --check-solc-version Check the installed solc version
  47. """,
  48. 'notes': """
  49. The owner address must be in checksummed format
  50. """
  51. }
  52. }
  53. # ERC Token Standard #20 Interface
  54. # https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
  55. solidity_code_template = """
  56. pragma solidity %s;
  57. contract SafeMath {
  58. function safeAdd(uint a, uint b) public pure returns (uint c) {
  59. c = a + b;
  60. require(c >= a);
  61. }
  62. function safeSub(uint a, uint b) public pure returns (uint c) {
  63. require(b <= a);
  64. c = a - b;
  65. }
  66. function safeMul(uint a, uint b) public pure returns (uint c) {
  67. c = a * b;
  68. require(a == 0 || c / a == b);
  69. }
  70. function safeDiv(uint a, uint b) public pure returns (uint c) {
  71. require(b > 0);
  72. c = a / b;
  73. }
  74. }
  75. abstract contract ERC20Interface {
  76. function totalSupply() public virtual returns (uint);
  77. function balanceOf(address tokenOwner) public virtual returns (uint balance);
  78. function allowance(address tokenOwner, address spender) public virtual returns (uint remaining);
  79. function transfer(address to, uint tokens) public virtual returns (bool success);
  80. function approve(address spender, uint tokens) public virtual returns (bool success);
  81. function transferFrom(address from, address to, uint tokens) public virtual returns (bool success);
  82. event Transfer(address indexed from, address indexed to, uint tokens);
  83. event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
  84. }
  85. contract Owned {
  86. address public owner;
  87. address public newOwner;
  88. event OwnershipTransferred(address indexed _from, address indexed _to);
  89. constructor() public {
  90. owner = msg.sender;
  91. }
  92. modifier onlyOwner {
  93. require(msg.sender == owner);
  94. _;
  95. }
  96. function transferOwnership(address _newOwner) public onlyOwner {
  97. newOwner = _newOwner;
  98. }
  99. function acceptOwnership() public {
  100. require(msg.sender == newOwner);
  101. emit OwnershipTransferred(owner, newOwner);
  102. owner = newOwner;
  103. newOwner = address(0);
  104. }
  105. }
  106. // ----------------------------------------------------------------------------
  107. // ERC20 Token, with the addition of symbol, name and decimals and assisted
  108. // token transfers
  109. // ----------------------------------------------------------------------------
  110. contract Token is ERC20Interface, Owned, SafeMath {
  111. string public symbol;
  112. string public name;
  113. uint8 public decimals;
  114. uint public _totalSupply;
  115. mapping(address => uint) balances;
  116. mapping(address => mapping(address => uint)) allowed;
  117. constructor() public {
  118. symbol = "$symbol";
  119. name = "$name";
  120. decimals = $decimals;
  121. _totalSupply = $supply;
  122. balances[$owner_addr] = _totalSupply;
  123. emit Transfer(address(0), $owner_addr, _totalSupply);
  124. }
  125. function totalSupply() public override returns (uint) {
  126. return _totalSupply - balances[address(0)];
  127. }
  128. function balanceOf(address tokenOwner) public override returns (uint balance) {
  129. return balances[tokenOwner];
  130. }
  131. function transfer(address to, uint tokens) public override returns (bool success) {
  132. balances[msg.sender] = safeSub(balances[msg.sender], tokens);
  133. balances[to] = safeAdd(balances[to], tokens);
  134. emit Transfer(msg.sender, to, tokens);
  135. return true;
  136. }
  137. function approve(address spender, uint tokens) public override returns (bool success) {
  138. allowed[msg.sender][spender] = tokens;
  139. emit Approval(msg.sender, spender, tokens);
  140. return true;
  141. }
  142. function transferFrom(address from, address to, uint tokens) public override returns (bool success) {
  143. balances[from] = safeSub(balances[from], tokens);
  144. allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
  145. balances[to] = safeAdd(balances[to], tokens);
  146. emit Transfer(from, to, tokens);
  147. return true;
  148. }
  149. function allowance(address tokenOwner, address spender) public override returns (uint remaining) {
  150. return allowed[tokenOwner][spender];
  151. }
  152. // Owner can transfer out any accidentally sent ERC20 tokens
  153. function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
  154. return ERC20Interface(tokenAddress).transfer(owner, tokens);
  155. }
  156. }
  157. """ % req_solc_ver_pat
  158. def create_src(proto,template,token_data,owner_addr):
  159. def gen():
  160. for k in token_data.fields:
  161. field = getattr(token_data,k)
  162. if k == 'owner_addr':
  163. from mmgen.addr import is_coin_addr
  164. if not is_coin_addr( proto, owner_addr.lower() ):
  165. die(1,f'{owner_addr}: not a valid {proto.coin} coin address')
  166. val = '0x' + owner_addr
  167. else:
  168. val = (
  169. getattr(opt,k) if getattr(opt,k,None) else
  170. field.default if field.default is not None else
  171. die(1,f'The --{k} option must be specified')
  172. )
  173. if not field.test(val):
  174. die(1,f'{val!r}: invalid parameter for option --{k}')
  175. yield(k,field.conversion(val))
  176. from string import Template
  177. return Template(template).substitute(**dict(gen()))
  178. def check_solc_version():
  179. """
  180. The output is used by other programs, so write to stdout only
  181. """
  182. try:
  183. cp = run(['solc','--version'],check=True,stdout=PIPE)
  184. except:
  185. msg('solc missing or could not be executed') # this must go to stderr
  186. return False
  187. if cp.returncode != 0:
  188. Msg('solc exited with error')
  189. return False
  190. line = cp.stdout.decode().splitlines()[1]
  191. version_str = re.sub(r'Version:\s*','',line)
  192. m = re.match(r'(\d+)\.(\d+)\.(\d+)',version_str)
  193. if not m:
  194. Msg(f'Unrecognized solc version string: {version_str}')
  195. return False
  196. from semantic_version import Version,NpmSpec
  197. version = Version('{}.{}.{}'.format(*m.groups()))
  198. if version in NpmSpec(req_solc_ver_pat):
  199. Msg(str(version))
  200. return True
  201. else:
  202. Msg(f'solc version ({version_str}) does not match requirement ({req_solc_ver_pat})')
  203. return False
  204. def compile_code(code):
  205. cmd = ['solc','--optimize','--bin','--overwrite']
  206. if not opt.stdout:
  207. cmd += ['--output-dir', opt.outdir or '.']
  208. cmd += ['-']
  209. msg(f"Executing: {' '.join(cmd)}")
  210. cp = run(cmd,input=code.encode(),stdout=PIPE,stderr=PIPE)
  211. out = cp.stdout.decode().replace('\r','')
  212. err = cp.stderr.decode().replace('\r','').strip()
  213. if cp.returncode != 0:
  214. rmsg('Solidity compiler produced the following error:')
  215. msg(err)
  216. die(4,f'Solidity compiler exited with error (return val: {cp.returncode})')
  217. if err:
  218. ymsg('Solidity compiler produced the following warning:')
  219. msg(err)
  220. if opt.stdout:
  221. o = out.split('\n')
  222. return {k:o[i+2] for k in ('SafeMath','Owned','Token') for i in range(len(o)) if k in o[i]}
  223. else:
  224. vmsg(out)
  225. if __name__ == '__main__':
  226. cmd_args = opts.init(opts_data)
  227. if opt.check_solc_version:
  228. sys.exit(0 if check_solc_version() else 1)
  229. from mmgen.protocol import init_proto_from_opts
  230. proto = init_proto_from_opts()
  231. if not proto.coin in ('ETH','ETC'):
  232. die(1,'--coin option must be ETH or ETC')
  233. if not len(cmd_args) == 1:
  234. opts.usage()
  235. code = create_src( proto, solidity_code_template, token_data, cmd_args[0] )
  236. if opt.preprocess:
  237. Msg(code)
  238. sys.exit(0)
  239. out = compile_code(code)
  240. if opt.stdout:
  241. print(json.dumps(out))
  242. msg('Contract successfully compiled')