create-token.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. #!/usr/bin/env python3
  2. #
  3. # MMGen Wallet, a terminal-based cryptocurrency wallet
  4. # Copyright (C)2013-2024 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.25'
  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. // SPDX-License-Identifier: GPL-3.0-or-later
  64. pragma solidity %s;
  65. contract SafeMath {
  66. function safeAdd(uint a, uint b) public pure returns (uint c) {
  67. c = a + b;
  68. require(c >= a);
  69. }
  70. function safeSub(uint a, uint b) public pure returns (uint c) {
  71. require(b <= a);
  72. c = a - b;
  73. }
  74. function safeMul(uint a, uint b) public pure returns (uint c) {
  75. c = a * b;
  76. require(a == 0 || c / a == b);
  77. }
  78. function safeDiv(uint a, uint b) public pure returns (uint c) {
  79. require(b > 0);
  80. c = a / b;
  81. }
  82. }
  83. abstract contract ERC20Interface {
  84. function totalSupply() public virtual returns (uint);
  85. function balanceOf(address tokenOwner) public virtual returns (uint balance);
  86. function allowance(address tokenOwner, address spender) public virtual returns (uint remaining);
  87. function transfer(address to, uint tokens) public virtual returns (bool success);
  88. function approve(address spender, uint tokens) public virtual returns (bool success);
  89. function transferFrom(address from, address to, uint tokens) public virtual returns (bool success);
  90. event Transfer(address indexed from, address indexed to, uint tokens);
  91. event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
  92. }
  93. contract Owned {
  94. address public owner;
  95. address public newOwner;
  96. event OwnershipTransferred(address indexed _from, address indexed _to);
  97. constructor() {
  98. owner = msg.sender;
  99. }
  100. modifier onlyOwner {
  101. require(msg.sender == owner);
  102. _;
  103. }
  104. function transferOwnership(address _newOwner) public onlyOwner {
  105. newOwner = _newOwner;
  106. }
  107. function acceptOwnership() public {
  108. require(msg.sender == newOwner);
  109. emit OwnershipTransferred(owner, newOwner);
  110. owner = newOwner;
  111. newOwner = address(0);
  112. }
  113. }
  114. // ----------------------------------------------------------------------------
  115. // ERC20 Token, with the addition of symbol, name and decimals and assisted
  116. // token transfers
  117. // ----------------------------------------------------------------------------
  118. contract Token is ERC20Interface, Owned, SafeMath {
  119. string public symbol;
  120. string public name;
  121. uint8 public decimals;
  122. uint public _totalSupply;
  123. mapping(address => uint) balances;
  124. mapping(address => mapping(address => uint)) allowed;
  125. constructor() {
  126. symbol = "$symbol";
  127. name = "$name";
  128. decimals = $decimals;
  129. _totalSupply = $supply;
  130. balances[$owner_addr] = _totalSupply;
  131. emit Transfer(address(0), $owner_addr, _totalSupply);
  132. }
  133. function totalSupply() public view override returns (uint) {
  134. return _totalSupply - balances[address(0)];
  135. }
  136. function balanceOf(address tokenOwner) public view override returns (uint balance) {
  137. return balances[tokenOwner];
  138. }
  139. function transfer(address to, uint tokens) public override returns (bool success) {
  140. balances[msg.sender] = safeSub(balances[msg.sender], tokens);
  141. balances[to] = safeAdd(balances[to], tokens);
  142. emit Transfer(msg.sender, to, tokens);
  143. return true;
  144. }
  145. function approve(address spender, uint tokens) public override returns (bool success) {
  146. allowed[msg.sender][spender] = tokens;
  147. emit Approval(msg.sender, spender, tokens);
  148. return true;
  149. }
  150. function transferFrom(address from, address to, uint tokens) public override returns (bool success) {
  151. balances[from] = safeSub(balances[from], tokens);
  152. allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
  153. balances[to] = safeAdd(balances[to], tokens);
  154. emit Transfer(from, to, tokens);
  155. return true;
  156. }
  157. function allowance(address tokenOwner, address spender) public view override returns (uint remaining) {
  158. return allowed[tokenOwner][spender];
  159. }
  160. // Owner can transfer out any accidentally sent ERC20 tokens
  161. function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
  162. return ERC20Interface(tokenAddress).transfer(owner, tokens);
  163. }
  164. }
  165. """ % req_solc_ver_pat
  166. def create_src(cfg, template, token_data):
  167. def gen():
  168. for k in token_data.fields:
  169. field = getattr(token_data, k)
  170. if k == 'owner_addr':
  171. owner_addr = cfg._args[0]
  172. from mmgen.addr import is_coin_addr
  173. if not is_coin_addr(cfg._proto, owner_addr.lower()):
  174. die(1, f'{owner_addr}: not a valid {cfg._proto.coin} coin address')
  175. val = '0x' + owner_addr
  176. else:
  177. val = (
  178. getattr(cfg, k)
  179. or getattr(field, 'default', None)
  180. or die(1, f'The --{k} option must be specified')
  181. )
  182. if not field.test(val):
  183. die(1, f'{val!r}: invalid parameter for option --{k}')
  184. yield (k, field.conversion(val))
  185. from string import Template
  186. return Template(template).substitute(**dict(gen()))
  187. def check_solc_version():
  188. """
  189. The output is used by other programs, so write to stdout only
  190. """
  191. try:
  192. cp = run(['solc', '--version'], check=True, stdout=PIPE)
  193. except:
  194. msg('solc missing or could not be executed') # this must go to stderr
  195. return False
  196. if cp.returncode != 0:
  197. Msg('solc exited with error')
  198. return False
  199. line = cp.stdout.decode().splitlines()[1]
  200. version_str = re.sub(r'Version:\s*', '', line)
  201. m = re.match(r'(\d+)\.(\d+)\.(\d+)', version_str)
  202. if not m:
  203. Msg(f'Unrecognized solc version string: {version_str}')
  204. return False
  205. from semantic_version import Version, NpmSpec
  206. version = Version('{}.{}.{}'.format(*m.groups()))
  207. if version in NpmSpec(req_solc_ver_pat):
  208. Msg(str(version))
  209. return True
  210. else:
  211. Msg(f'solc version ({version_str}) does not match requirement ({req_solc_ver_pat})')
  212. return False
  213. def compile_code(cfg, code):
  214. cmd = ['solc', '--optimize', '--bin', '--overwrite', '--evm-version=constantinople']
  215. if not cfg.stdout:
  216. cmd += ['--output-dir', cfg.outdir or '.']
  217. cmd += ['-']
  218. msg(f"Executing: {' '.join(cmd)}")
  219. cp = run(cmd, input=code.encode(), stdout=PIPE, stderr=PIPE)
  220. out = cp.stdout.decode().replace('\r', '')
  221. err = cp.stderr.decode().replace('\r', '').strip()
  222. if cp.returncode != 0:
  223. rmsg('Solidity compiler produced the following error:')
  224. msg(err)
  225. die(4, f'Solidity compiler exited with error (return val: {cp.returncode})')
  226. if err:
  227. ymsg('Solidity compiler produced the following warning:')
  228. msg(err)
  229. if cfg.stdout:
  230. o = out.split('\n')
  231. return {k:o[i+2] for k in ('SafeMath', 'Owned', 'Token') for i in range(len(o)) if k in o[i]}
  232. else:
  233. cfg._util.vmsg(out)
  234. def main():
  235. cfg = Config(opts_data=opts_data)
  236. if cfg.check_solc_version:
  237. sys.exit(0 if check_solc_version() else 1)
  238. if not cfg._proto.coin in ('ETH', 'ETC'):
  239. die(1, '--coin option must be ETH or ETC')
  240. if not len(cfg._args) == 1:
  241. cfg._usage()
  242. code = create_src(cfg, solidity_code_template, token_data)
  243. if cfg.preprocess:
  244. Msg(code)
  245. sys.exit(0)
  246. out = compile_code(cfg, code)
  247. if cfg.stdout:
  248. print(json.dumps(out))
  249. msg('Contract successfully compiled')
  250. if __name__ == '__main__':
  251. launch(func=main)