create-token.py 9.4 KB

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