create-token.py 9.5 KB

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