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