create-token.py 9.4 KB

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