mmgen-pywallet 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677
  1. #!/usr/bin/env python
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C) 2013 by philemon <mmgen-py@yandex.com>
  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. mmgen-pywallet: Dump contents of a bitcoind wallet to file
  20. """
  21. # Changes by Philemon:
  22. # password entry at prompt
  23. # dump keys, addresses or keys for specified addresses (output in flat list)
  24. # PyWallet 1.2.1 (Public Domain)
  25. # http://github.com/joric/pywallet
  26. # Most of the actual PyWallet code placed in the public domain.
  27. # PyWallet includes portions of free software, listed below.
  28. # BitcoinTools (wallet.dat handling code, MIT License)
  29. # https://github.com/gavinandresen/bitcointools
  30. # Copyright (c) 2010 Gavin Andresen
  31. # python-ecdsa (EC_KEY implementation, MIT License)
  32. # http://github.com/warner/python-ecdsa
  33. # "python-ecdsa" Copyright (c) 2010 Brian Warner
  34. # Portions written in 2005 by Peter Pearson and placed in the public domain.
  35. # SlowAES (aes.py code, Apache 2 License)
  36. # http://code.google.com/p/slowaes/
  37. # Copyright (c) 2008, Josh Davis (http://www.josh-davis.org),
  38. # Alex Martelli (http://www.aleax.it)
  39. # Ported from C code written by Laurent Haan (http://www.progressive-coding.com)
  40. from mmgen.Opts import *
  41. from mmgen.util import msg
  42. import mmgen.config as g
  43. from bsddb.db import *
  44. import sys, time
  45. import json
  46. import logging
  47. import struct
  48. import StringIO
  49. import traceback
  50. import socket
  51. import types
  52. import string
  53. import exceptions
  54. import hashlib
  55. import random
  56. import math
  57. max_version = 60000
  58. addrtype = 0
  59. json_db = {}
  60. private_keys = []
  61. password = None
  62. prog_name = sys.argv[0].split("/")[-1]
  63. help_data = {
  64. 'prog_name': prog_name,
  65. 'desc': "Dump contents of a bitcoind wallet to file",
  66. 'usage': "[opts] <bitcoind wallet file>",
  67. 'options': """
  68. -h, --help Print this help message
  69. -d, --outdir= d Specify an alternate directory 'd' for output
  70. -e, --echo-passphrase Display passphrase on screen upon entry
  71. -j, --json Dump wallet in json format
  72. -k, --keys Dump all private keys (flat list)
  73. -a, --addrs Dump all addresses (flat list)
  74. -K, --keysforaddrs= f Dump private keys for addresses listed in file 'f'
  75. -P, --passwd-file= f Get passphrase from file 'f'
  76. -S, --stdout Dump to stdout rather than file
  77. """
  78. }
  79. opts,cmd_args = parse_opts(sys.argv,help_data)
  80. if len(cmd_args) == 1:
  81. from mmgen.util import check_infile
  82. check_infile(cmd_args[0])
  83. else:
  84. usage(help_data)
  85. if ('json' not in opts and 'keys' not in opts
  86. and 'addrs' not in opts and 'keysforaddrs' not in opts):
  87. usage(help_data)
  88. # from the SlowAES project, http://code.google.com/p/slowaes (aes.py)
  89. def append_PKCS7_padding(s):
  90. """return s padded to a multiple of 16-bytes by PKCS7 padding"""
  91. numpads = 16 - (len(s)%16)
  92. return s + numpads*chr(numpads)
  93. def strip_PKCS7_padding(s):
  94. """return s stripped of PKCS7 padding"""
  95. if len(s)%16 or not s:
  96. raise ValueError("String of len %d can't be PCKS7-padded" % len(s))
  97. numpads = ord(s[-1])
  98. if numpads > 16:
  99. raise ValueError("String ending with %r can't be PCKS7-padded" % s[-1])
  100. return s[:-numpads]
  101. class AES(object):
  102. # valid key sizes
  103. keySize = dict(SIZE_128=16, SIZE_192=24, SIZE_256=32)
  104. # Rijndael S-box
  105. sbox = [0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67,
  106. 0x2b, 0xfe, 0xd7, 0xab, 0x76, 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59,
  107. 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, 0xb7,
  108. 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1,
  109. 0x71, 0xd8, 0x31, 0x15, 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05,
  110. 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, 0x09, 0x83,
  111. 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29,
  112. 0xe3, 0x2f, 0x84, 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b,
  113. 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, 0xd0, 0xef, 0xaa,
  114. 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c,
  115. 0x9f, 0xa8, 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc,
  116. 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, 0xcd, 0x0c, 0x13, 0xec,
  117. 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19,
  118. 0x73, 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee,
  119. 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, 0xe0, 0x32, 0x3a, 0x0a, 0x49,
  120. 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
  121. 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4,
  122. 0xea, 0x65, 0x7a, 0xae, 0x08, 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6,
  123. 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, 0x70,
  124. 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9,
  125. 0x86, 0xc1, 0x1d, 0x9e, 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e,
  126. 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, 0x8c, 0xa1,
  127. 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0,
  128. 0x54, 0xbb, 0x16]
  129. # Rijndael Inverted S-box
  130. rsbox = [0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3,
  131. 0x9e, 0x81, 0xf3, 0xd7, 0xfb , 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f,
  132. 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb , 0x54,
  133. 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b,
  134. 0x42, 0xfa, 0xc3, 0x4e , 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24,
  135. 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25 , 0x72, 0xf8,
  136. 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d,
  137. 0x65, 0xb6, 0x92 , 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda,
  138. 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84 , 0x90, 0xd8, 0xab,
  139. 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3,
  140. 0x45, 0x06 , 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1,
  141. 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b , 0x3a, 0x91, 0x11, 0x41,
  142. 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6,
  143. 0x73 , 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9,
  144. 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e , 0x47, 0xf1, 0x1a, 0x71, 0x1d,
  145. 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b ,
  146. 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0,
  147. 0xfe, 0x78, 0xcd, 0x5a, 0xf4 , 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07,
  148. 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f , 0x60,
  149. 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f,
  150. 0x93, 0xc9, 0x9c, 0xef , 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5,
  151. 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61 , 0x17, 0x2b,
  152. 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55,
  153. 0x21, 0x0c, 0x7d]
  154. def getSBoxValue(self,num):
  155. """Retrieves a given S-Box Value"""
  156. return self.sbox[num]
  157. def getSBoxInvert(self,num):
  158. """Retrieves a given Inverted S-Box Value"""
  159. return self.rsbox[num]
  160. def rotate(self, word):
  161. """ Rijndael's key schedule rotate operation.
  162. Rotate a word eight bits to the left: eg, rotate(1d2c3a4f) == 2c3a4f1d
  163. Word is an char list of size 4 (32 bits overall).
  164. """
  165. return word[1:] + word[:1]
  166. # Rijndael Rcon
  167. Rcon = [0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36,
  168. 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97,
  169. 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72,
  170. 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66,
  171. 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04,
  172. 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d,
  173. 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3,
  174. 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61,
  175. 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a,
  176. 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40,
  177. 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc,
  178. 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5,
  179. 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a,
  180. 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d,
  181. 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c,
  182. 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35,
  183. 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4,
  184. 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc,
  185. 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04, 0x08,
  186. 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a,
  187. 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d,
  188. 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2,
  189. 0x9f, 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74,
  190. 0xe8, 0xcb ]
  191. def getRconValue(self, num):
  192. """Retrieves a given Rcon Value"""
  193. return self.Rcon[num]
  194. def core(self, word, iteration):
  195. """Key schedule core."""
  196. # rotate the 32-bit word 8 bits to the left
  197. word = self.rotate(word)
  198. # apply S-Box substitution on all 4 parts of the 32-bit word
  199. for i in range(4):
  200. word[i] = self.getSBoxValue(word[i])
  201. # XOR the output of the rcon operation with i to the first part
  202. # (leftmost) only
  203. word[0] = word[0] ^ self.getRconValue(iteration)
  204. return word
  205. def expandKey(self, key, size, expandedKeySize):
  206. """Rijndael's key expansion.
  207. Expands an 128,192,256 key into an 176,208,240 bytes key
  208. expandedKey is a char list of large enough size,
  209. key is the non-expanded key.
  210. """
  211. # current expanded keySize, in bytes
  212. currentSize = 0
  213. rconIteration = 1
  214. expandedKey = [0] * expandedKeySize
  215. # set the 16, 24, 32 bytes of the expanded key to the input key
  216. for j in range(size):
  217. expandedKey[j] = key[j]
  218. currentSize += size
  219. while currentSize < expandedKeySize:
  220. # assign the previous 4 bytes to the temporary value t
  221. t = expandedKey[currentSize-4:currentSize]
  222. # every 16,24,32 bytes we apply the core schedule to t
  223. # and increment rconIteration afterwards
  224. if currentSize % size == 0:
  225. t = self.core(t, rconIteration)
  226. rconIteration += 1
  227. # For 256-bit keys, we add an extra sbox to the calculation
  228. if size == self.keySize["SIZE_256"] and ((currentSize % size) == 16):
  229. for l in range(4): t[l] = self.getSBoxValue(t[l])
  230. # We XOR t with the four-byte block 16,24,32 bytes before the new
  231. # expanded key. This becomes the next four bytes in the expanded
  232. # key.
  233. for m in range(4):
  234. expandedKey[currentSize] = expandedKey[currentSize - size] ^ \
  235. t[m]
  236. currentSize += 1
  237. return expandedKey
  238. def addRoundKey(self, state, roundKey):
  239. """Adds (XORs) the round key to the state."""
  240. for i in range(16):
  241. state[i] ^= roundKey[i]
  242. return state
  243. def createRoundKey(self, expandedKey, roundKeyPointer):
  244. """Create a round key.
  245. Creates a round key from the given expanded key and the
  246. position within the expanded key.
  247. """
  248. roundKey = [0] * 16
  249. for i in range(4):
  250. for j in range(4):
  251. roundKey[j*4+i] = expandedKey[roundKeyPointer + i*4 + j]
  252. return roundKey
  253. def galois_multiplication(self, a, b):
  254. """Galois multiplication of 8 bit characters a and b."""
  255. p = 0
  256. for counter in range(8):
  257. if b & 1: p ^= a
  258. hi_bit_set = a & 0x80
  259. a <<= 1
  260. # keep a 8 bit
  261. a &= 0xFF
  262. if hi_bit_set:
  263. a ^= 0x1b
  264. b >>= 1
  265. return p
  266. #
  267. # substitute all the values from the state with the value in the SBox
  268. # using the state value as index for the SBox
  269. #
  270. def subBytes(self, state, isInv):
  271. if isInv: getter = self.getSBoxInvert
  272. else: getter = self.getSBoxValue
  273. for i in range(16): state[i] = getter(state[i])
  274. return state
  275. # iterate over the 4 rows and call shiftRow() with that row
  276. def shiftRows(self, state, isInv):
  277. for i in range(4):
  278. state = self.shiftRow(state, i*4, i, isInv)
  279. return state
  280. # each iteration shifts the row to the left by 1
  281. def shiftRow(self, state, statePointer, nbr, isInv):
  282. for i in range(nbr):
  283. if isInv:
  284. state[statePointer:statePointer+4] = \
  285. state[statePointer+3:statePointer+4] + \
  286. state[statePointer:statePointer+3]
  287. else:
  288. state[statePointer:statePointer+4] = \
  289. state[statePointer+1:statePointer+4] + \
  290. state[statePointer:statePointer+1]
  291. return state
  292. # galois multiplication of the 4x4 matrix
  293. def mixColumns(self, state, isInv):
  294. # iterate over the 4 columns
  295. for i in range(4):
  296. # construct one column by slicing over the 4 rows
  297. column = state[i:i+16:4]
  298. # apply the mixColumn on one column
  299. column = self.mixColumn(column, isInv)
  300. # put the values back into the state
  301. state[i:i+16:4] = column
  302. return state
  303. # galois multiplication of 1 column of the 4x4 matrix
  304. def mixColumn(self, column, isInv):
  305. if isInv: mult = [14, 9, 13, 11]
  306. else: mult = [2, 1, 1, 3]
  307. cpy = list(column)
  308. g = self.galois_multiplication
  309. column[0] = g(cpy[0], mult[0]) ^ g(cpy[3], mult[1]) ^ \
  310. g(cpy[2], mult[2]) ^ g(cpy[1], mult[3])
  311. column[1] = g(cpy[1], mult[0]) ^ g(cpy[0], mult[1]) ^ \
  312. g(cpy[3], mult[2]) ^ g(cpy[2], mult[3])
  313. column[2] = g(cpy[2], mult[0]) ^ g(cpy[1], mult[1]) ^ \
  314. g(cpy[0], mult[2]) ^ g(cpy[3], mult[3])
  315. column[3] = g(cpy[3], mult[0]) ^ g(cpy[2], mult[1]) ^ \
  316. g(cpy[1], mult[2]) ^ g(cpy[0], mult[3])
  317. return column
  318. # applies the 4 operations of the forward round in sequence
  319. def aes_round(self, state, roundKey):
  320. state = self.subBytes(state, False)
  321. state = self.shiftRows(state, False)
  322. state = self.mixColumns(state, False)
  323. state = self.addRoundKey(state, roundKey)
  324. return state
  325. # applies the 4 operations of the inverse round in sequence
  326. def aes_invRound(self, state, roundKey):
  327. state = self.shiftRows(state, True)
  328. state = self.subBytes(state, True)
  329. state = self.addRoundKey(state, roundKey)
  330. state = self.mixColumns(state, True)
  331. return state
  332. # Perform the initial operations, the standard round, and the final
  333. # operations of the forward aes, creating a round key for each round
  334. def aes_main(self, state, expandedKey, nbrRounds):
  335. state = self.addRoundKey(state, self.createRoundKey(expandedKey, 0))
  336. i = 1
  337. while i < nbrRounds:
  338. state = self.aes_round(state, self.createRoundKey(expandedKey, 16*i))
  339. i += 1
  340. state = self.subBytes(state, False)
  341. state = self.shiftRows(state, False)
  342. state = self.addRoundKey(state, self.createRoundKey(expandedKey, 16*nbrRounds))
  343. return state
  344. # Perform the initial operations, the standard round, and the final
  345. # operations of the inverse aes, creating a round key for each round
  346. def aes_invMain(self, state, expandedKey, nbrRounds):
  347. state = self.addRoundKey(state, self.createRoundKey(expandedKey, 16*nbrRounds))
  348. i = nbrRounds - 1
  349. while i > 0:
  350. state = self.aes_invRound(state, self.createRoundKey(expandedKey, 16*i))
  351. i -= 1
  352. state = self.shiftRows(state, True)
  353. state = self.subBytes(state, True)
  354. state = self.addRoundKey(state, self.createRoundKey(expandedKey, 0))
  355. return state
  356. # encrypts a 128 bit input block against the given key of size specified
  357. def encrypt(self, iput, key, size):
  358. output = [0] * 16
  359. # the number of rounds
  360. nbrRounds = 0
  361. # the 128 bit block to encode
  362. block = [0] * 16
  363. # set the number of rounds
  364. if size == self.keySize["SIZE_128"]: nbrRounds = 10
  365. elif size == self.keySize["SIZE_192"]: nbrRounds = 12
  366. elif size == self.keySize["SIZE_256"]: nbrRounds = 14
  367. else: return None
  368. # the expanded keySize
  369. expandedKeySize = 16*(nbrRounds+1)
  370. # Set the block values, for the block:
  371. # a0,0 a0,1 a0,2 a0,3
  372. # a1,0 a1,1 a1,2 a1,3
  373. # a2,0 a2,1 a2,2 a2,3
  374. # a3,0 a3,1 a3,2 a3,3
  375. # the mapping order is a0,0 a1,0 a2,0 a3,0 a0,1 a1,1 ... a2,3 a3,3
  376. #
  377. # iterate over the columns
  378. for i in range(4):
  379. # iterate over the rows
  380. for j in range(4):
  381. block[(i+(j*4))] = iput[(i*4)+j]
  382. # expand the key into an 176, 208, 240 bytes key
  383. # the expanded key
  384. expandedKey = self.expandKey(key, size, expandedKeySize)
  385. # encrypt the block using the expandedKey
  386. block = self.aes_main(block, expandedKey, nbrRounds)
  387. # unmap the block again into the output
  388. for k in range(4):
  389. # iterate over the rows
  390. for l in range(4):
  391. output[(k*4)+l] = block[(k+(l*4))]
  392. return output
  393. # decrypts a 128 bit input block against the given key of size specified
  394. def decrypt(self, iput, key, size):
  395. output = [0] * 16
  396. # the number of rounds
  397. nbrRounds = 0
  398. # the 128 bit block to decode
  399. block = [0] * 16
  400. # set the number of rounds
  401. if size == self.keySize["SIZE_128"]: nbrRounds = 10
  402. elif size == self.keySize["SIZE_192"]: nbrRounds = 12
  403. elif size == self.keySize["SIZE_256"]: nbrRounds = 14
  404. else: return None
  405. # the expanded keySize
  406. expandedKeySize = 16*(nbrRounds+1)
  407. # Set the block values, for the block:
  408. # a0,0 a0,1 a0,2 a0,3
  409. # a1,0 a1,1 a1,2 a1,3
  410. # a2,0 a2,1 a2,2 a2,3
  411. # a3,0 a3,1 a3,2 a3,3
  412. # the mapping order is a0,0 a1,0 a2,0 a3,0 a0,1 a1,1 ... a2,3 a3,3
  413. # iterate over the columns
  414. for i in range(4):
  415. # iterate over the rows
  416. for j in range(4):
  417. block[(i+(j*4))] = iput[(i*4)+j]
  418. # expand the key into an 176, 208, 240 bytes key
  419. expandedKey = self.expandKey(key, size, expandedKeySize)
  420. # decrypt the block using the expandedKey
  421. block = self.aes_invMain(block, expandedKey, nbrRounds)
  422. # unmap the block again into the output
  423. for k in range(4):
  424. # iterate over the rows
  425. for l in range(4):
  426. output[(k*4)+l] = block[(k+(l*4))]
  427. return output
  428. class AESModeOfOperation(object):
  429. aes = AES()
  430. # structure of supported modes of operation
  431. modeOfOperation = dict(OFB=0, CFB=1, CBC=2)
  432. # converts a 16 character string into a number array
  433. def convertString(self, string, start, end, mode):
  434. if end - start > 16: end = start + 16
  435. if mode == self.modeOfOperation["CBC"]: ar = [0] * 16
  436. else: ar = []
  437. i = start
  438. j = 0
  439. while len(ar) < end - start:
  440. ar.append(0)
  441. while i < end:
  442. ar[j] = ord(string[i])
  443. j += 1
  444. i += 1
  445. return ar
  446. # Mode of Operation Encryption
  447. # stringIn - Input String
  448. # mode - mode of type modeOfOperation
  449. # hexKey - a hex key of the bit length size
  450. # size - the bit length of the key
  451. # hexIV - the 128 bit hex Initilization Vector
  452. def encrypt(self, stringIn, mode, key, size, IV):
  453. if len(key) % size:
  454. return None
  455. if len(IV) % 16:
  456. return None
  457. # the AES input/output
  458. plaintext = []
  459. iput = [0] * 16
  460. output = []
  461. ciphertext = [0] * 16
  462. # the output cipher string
  463. cipherOut = []
  464. # char firstRound
  465. firstRound = True
  466. if stringIn != None:
  467. for j in range(int(math.ceil(float(len(stringIn))/16))):
  468. start = j*16
  469. end = j*16+16
  470. if end > len(stringIn):
  471. end = len(stringIn)
  472. plaintext = self.convertString(stringIn, start, end, mode)
  473. # print 'PT@%s:%s' % (j, plaintext)
  474. if mode == self.modeOfOperation["CFB"]:
  475. if firstRound:
  476. output = self.aes.encrypt(IV, key, size)
  477. firstRound = False
  478. else:
  479. output = self.aes.encrypt(iput, key, size)
  480. for i in range(16):
  481. if len(plaintext)-1 < i:
  482. ciphertext[i] = 0 ^ output[i]
  483. elif len(output)-1 < i:
  484. ciphertext[i] = plaintext[i] ^ 0
  485. elif len(plaintext)-1 < i and len(output) < i:
  486. ciphertext[i] = 0 ^ 0
  487. else:
  488. ciphertext[i] = plaintext[i] ^ output[i]
  489. for k in range(end-start):
  490. cipherOut.append(ciphertext[k])
  491. iput = ciphertext
  492. elif mode == self.modeOfOperation["OFB"]:
  493. if firstRound:
  494. output = self.aes.encrypt(IV, key, size)
  495. firstRound = False
  496. else:
  497. output = self.aes.encrypt(iput, key, size)
  498. for i in range(16):
  499. if len(plaintext)-1 < i:
  500. ciphertext[i] = 0 ^ output[i]
  501. elif len(output)-1 < i:
  502. ciphertext[i] = plaintext[i] ^ 0
  503. elif len(plaintext)-1 < i and len(output) < i:
  504. ciphertext[i] = 0 ^ 0
  505. else:
  506. ciphertext[i] = plaintext[i] ^ output[i]
  507. for k in range(end-start):
  508. cipherOut.append(ciphertext[k])
  509. iput = output
  510. elif mode == self.modeOfOperation["CBC"]:
  511. for i in range(16):
  512. if firstRound:
  513. iput[i] = plaintext[i] ^ IV[i]
  514. else:
  515. iput[i] = plaintext[i] ^ ciphertext[i]
  516. # print 'IP@%s:%s' % (j, iput)
  517. firstRound = False
  518. ciphertext = self.aes.encrypt(iput, key, size)
  519. # always 16 bytes because of the padding for CBC
  520. for k in range(16):
  521. cipherOut.append(ciphertext[k])
  522. return mode, len(stringIn), cipherOut
  523. # Mode of Operation Decryption
  524. # cipherIn - Encrypted String
  525. # originalsize - The unencrypted string length - required for CBC
  526. # mode - mode of type modeOfOperation
  527. # key - a number array of the bit length size
  528. # size - the bit length of the key
  529. # IV - the 128 bit number array Initilization Vector
  530. def decrypt(self, cipherIn, originalsize, mode, key, size, IV):
  531. # cipherIn = unescCtrlChars(cipherIn)
  532. if len(key) % size:
  533. return None
  534. if len(IV) % 16:
  535. return None
  536. # the AES input/output
  537. ciphertext = []
  538. iput = []
  539. output = []
  540. plaintext = [0] * 16
  541. # the output plain text string
  542. stringOut = ''
  543. # char firstRound
  544. firstRound = True
  545. if cipherIn != None:
  546. for j in range(int(math.ceil(float(len(cipherIn))/16))):
  547. start = j*16
  548. end = j*16+16
  549. if j*16+16 > len(cipherIn):
  550. end = len(cipherIn)
  551. ciphertext = cipherIn[start:end]
  552. if mode == self.modeOfOperation["CFB"]:
  553. if firstRound:
  554. output = self.aes.encrypt(IV, key, size)
  555. firstRound = False
  556. else:
  557. output = self.aes.encrypt(iput, key, size)
  558. for i in range(16):
  559. if len(output)-1 < i:
  560. plaintext[i] = 0 ^ ciphertext[i]
  561. elif len(ciphertext)-1 < i:
  562. plaintext[i] = output[i] ^ 0
  563. elif len(output)-1 < i and len(ciphertext) < i:
  564. plaintext[i] = 0 ^ 0
  565. else:
  566. plaintext[i] = output[i] ^ ciphertext[i]
  567. for k in range(end-start):
  568. stringOut += chr(plaintext[k])
  569. iput = ciphertext
  570. elif mode == self.modeOfOperation["OFB"]:
  571. if firstRound:
  572. output = self.aes.encrypt(IV, key, size)
  573. firstRound = False
  574. else:
  575. output = self.aes.encrypt(iput, key, size)
  576. for i in range(16):
  577. if len(output)-1 < i:
  578. plaintext[i] = 0 ^ ciphertext[i]
  579. elif len(ciphertext)-1 < i:
  580. plaintext[i] = output[i] ^ 0
  581. elif len(output)-1 < i and len(ciphertext) < i:
  582. plaintext[i] = 0 ^ 0
  583. else:
  584. plaintext[i] = output[i] ^ ciphertext[i]
  585. for k in range(end-start):
  586. stringOut += chr(plaintext[k])
  587. iput = output
  588. elif mode == self.modeOfOperation["CBC"]:
  589. output = self.aes.decrypt(ciphertext, key, size)
  590. for i in range(16):
  591. if firstRound:
  592. plaintext[i] = IV[i] ^ output[i]
  593. else:
  594. plaintext[i] = iput[i] ^ output[i]
  595. firstRound = False
  596. if originalsize is not None and originalsize < end:
  597. for k in range(originalsize-start):
  598. stringOut += chr(plaintext[k])
  599. else:
  600. for k in range(end-start):
  601. stringOut += chr(plaintext[k])
  602. iput = ciphertext
  603. return stringOut
  604. # end of aes.py code
  605. # pywallet crypter implementation
  606. crypter = None
  607. try:
  608. from Crypto.Cipher import AES
  609. crypter = 'pycrypto'
  610. except:
  611. pass
  612. class Crypter_pycrypto( object ):
  613. def SetKeyFromPassphrase(self, vKeyData, vSalt, nDerivIterations, nDerivationMethod):
  614. if nDerivationMethod != 0:
  615. return 0
  616. data = vKeyData + vSalt
  617. for i in xrange(nDerivIterations):
  618. data = hashlib.sha512(data).digest()
  619. self.SetKey(data[0:32])
  620. self.SetIV(data[32:32+16])
  621. return len(data)
  622. def SetKey(self, key):
  623. self.chKey = key
  624. def SetIV(self, iv):
  625. self.chIV = iv[0:16]
  626. def Encrypt(self, data):
  627. return AES.new(self.chKey,AES.MODE_CBC,self.chIV).encrypt(data)[0:32]
  628. def Decrypt(self, data):
  629. return AES.new(self.chKey,AES.MODE_CBC,self.chIV).decrypt(data)[0:32]
  630. try:
  631. if not crypter:
  632. import ctypes
  633. import ctypes.util
  634. ssl = ctypes.cdll.LoadLibrary (ctypes.util.find_library ('ssl') or 'libeay32')
  635. crypter = 'ssl'
  636. except:
  637. pass
  638. class Crypter_ssl(object):
  639. def __init__(self):
  640. self.chKey = ctypes.create_string_buffer (32)
  641. self.chIV = ctypes.create_string_buffer (16)
  642. def SetKeyFromPassphrase(self, vKeyData, vSalt, nDerivIterations, nDerivationMethod):
  643. if nDerivationMethod != 0:
  644. return 0
  645. strKeyData = ctypes.create_string_buffer (vKeyData)
  646. chSalt = ctypes.create_string_buffer (vSalt)
  647. return ssl.EVP_BytesToKey(ssl.EVP_aes_256_cbc(), ssl.EVP_sha512(), chSalt, strKeyData,
  648. len(vKeyData), nDerivIterations, ctypes.byref(self.chKey), ctypes.byref(self.chIV))
  649. def SetKey(self, key):
  650. self.chKey = ctypes.create_string_buffer(key)
  651. def SetIV(self, iv):
  652. self.chIV = ctypes.create_string_buffer(iv)
  653. def Encrypt(self, data):
  654. buf = ctypes.create_string_buffer(len(data) + 16)
  655. written = ctypes.c_int(0)
  656. final = ctypes.c_int(0)
  657. ctx = ssl.EVP_CIPHER_CTX_new()
  658. ssl.EVP_CIPHER_CTX_init(ctx)
  659. ssl.EVP_EncryptInit_ex(ctx, ssl.EVP_aes_256_cbc(), None, self.chKey, self.chIV)
  660. ssl.EVP_EncryptUpdate(ctx, buf, ctypes.byref(written), data, len(data))
  661. output = buf.raw[:written.value]
  662. ssl.EVP_EncryptFinal_ex(ctx, buf, ctypes.byref(final))
  663. output += buf.raw[:final.value]
  664. return output
  665. def Decrypt(self, data):
  666. buf = ctypes.create_string_buffer(len(data) + 16)
  667. written = ctypes.c_int(0)
  668. final = ctypes.c_int(0)
  669. ctx = ssl.EVP_CIPHER_CTX_new()
  670. ssl.EVP_CIPHER_CTX_init(ctx)
  671. ssl.EVP_DecryptInit_ex(ctx, ssl.EVP_aes_256_cbc(), None, self.chKey, self.chIV)
  672. ssl.EVP_DecryptUpdate(ctx, buf, ctypes.byref(written), data, len(data))
  673. output = buf.raw[:written.value]
  674. ssl.EVP_DecryptFinal_ex(ctx, buf, ctypes.byref(final))
  675. output += buf.raw[:final.value]
  676. return output
  677. class Crypter_pure(object):
  678. def __init__(self):
  679. self.m = AESModeOfOperation()
  680. self.cbc = self.m.modeOfOperation["CBC"]
  681. self.sz = self.m.aes.keySize["SIZE_256"]
  682. def SetKeyFromPassphrase(self, vKeyData, vSalt, nDerivIterations, nDerivationMethod):
  683. if nDerivationMethod != 0:
  684. return 0
  685. data = vKeyData + vSalt
  686. for i in xrange(nDerivIterations):
  687. data = hashlib.sha512(data).digest()
  688. self.SetKey(data[0:32])
  689. self.SetIV(data[32:32+16])
  690. return len(data)
  691. def SetKey(self, key):
  692. self.chKey = [ord(i) for i in key]
  693. def SetIV(self, iv):
  694. self.chIV = [ord(i) for i in iv]
  695. def Encrypt(self, data):
  696. mode, size, cypher = self.m.encrypt(data, self.cbc, self.chKey, self.sz, self.chIV)
  697. return ''.join(map(chr, cypher))
  698. def Decrypt(self, data):
  699. chData = [ord(i) for i in data]
  700. return self.m.decrypt(chData, self.sz, self.cbc, self.chKey, self.sz, self.chIV)
  701. # secp256k1
  702. _p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2FL
  703. _r = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141L
  704. _b = 0x0000000000000000000000000000000000000000000000000000000000000007L
  705. _a = 0x0000000000000000000000000000000000000000000000000000000000000000L
  706. _Gx = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798L
  707. _Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8L
  708. # python-ecdsa code (EC_KEY implementation)
  709. class CurveFp( object ):
  710. def __init__( self, p, a, b ):
  711. self.__p = p
  712. self.__a = a
  713. self.__b = b
  714. def p( self ):
  715. return self.__p
  716. def a( self ):
  717. return self.__a
  718. def b( self ):
  719. return self.__b
  720. def contains_point( self, x, y ):
  721. return ( y * y - ( x * x * x + self.__a * x + self.__b ) ) % self.__p == 0
  722. class Point( object ):
  723. def __init__( self, curve, x, y, order = None ):
  724. self.__curve = curve
  725. self.__x = x
  726. self.__y = y
  727. self.__order = order
  728. if self.__curve: assert self.__curve.contains_point( x, y )
  729. if order: assert self * order == INFINITY
  730. def __add__( self, other ):
  731. if other == INFINITY: return self
  732. if self == INFINITY: return other
  733. assert self.__curve == other.__curve
  734. if self.__x == other.__x:
  735. if ( self.__y + other.__y ) % self.__curve.p() == 0:
  736. return INFINITY
  737. else:
  738. return self.double()
  739. p = self.__curve.p()
  740. l = ( ( other.__y - self.__y ) * \
  741. inverse_mod( other.__x - self.__x, p ) ) % p
  742. x3 = ( l * l - self.__x - other.__x ) % p
  743. y3 = ( l * ( self.__x - x3 ) - self.__y ) % p
  744. return Point( self.__curve, x3, y3 )
  745. def __mul__( self, other ):
  746. def leftmost_bit( x ):
  747. assert x > 0
  748. result = 1L
  749. while result <= x: result = 2 * result
  750. return result / 2
  751. e = other
  752. if self.__order: e = e % self.__order
  753. if e == 0: return INFINITY
  754. if self == INFINITY: return INFINITY
  755. assert e > 0
  756. e3 = 3 * e
  757. negative_self = Point( self.__curve, self.__x, -self.__y, self.__order )
  758. i = leftmost_bit( e3 ) / 2
  759. result = self
  760. while i > 1:
  761. result = result.double()
  762. if ( e3 & i ) != 0 and ( e & i ) == 0: result = result + self
  763. if ( e3 & i ) == 0 and ( e & i ) != 0: result = result + negative_self
  764. i = i / 2
  765. return result
  766. def __rmul__( self, other ):
  767. return self * other
  768. def __str__( self ):
  769. if self == INFINITY: return "infinity"
  770. return "(%d,%d)" % ( self.__x, self.__y )
  771. def double( self ):
  772. if self == INFINITY:
  773. return INFINITY
  774. p = self.__curve.p()
  775. a = self.__curve.a()
  776. l = ( ( 3 * self.__x * self.__x + a ) * \
  777. inverse_mod( 2 * self.__y, p ) ) % p
  778. x3 = ( l * l - 2 * self.__x ) % p
  779. y3 = ( l * ( self.__x - x3 ) - self.__y ) % p
  780. return Point( self.__curve, x3, y3 )
  781. def x( self ):
  782. return self.__x
  783. def y( self ):
  784. return self.__y
  785. def curve( self ):
  786. return self.__curve
  787. def order( self ):
  788. return self.__order
  789. INFINITY = Point( None, None, None )
  790. def inverse_mod( a, m ):
  791. if a < 0 or m <= a: a = a % m
  792. c, d = a, m
  793. uc, vc, ud, vd = 1, 0, 0, 1
  794. while c != 0:
  795. q, c, d = divmod( d, c ) + ( c, )
  796. uc, vc, ud, vd = ud - q*uc, vd - q*vc, uc, vc
  797. assert d == 1
  798. if ud > 0: return ud
  799. else: return ud + m
  800. class Signature( object ):
  801. def __init__( self, r, s ):
  802. self.r = r
  803. self.s = s
  804. class Public_key( object ):
  805. def __init__( self, generator, point ):
  806. self.curve = generator.curve()
  807. self.generator = generator
  808. self.point = point
  809. n = generator.order()
  810. if not n:
  811. raise RuntimeError, "Generator point must have order."
  812. if not n * point == INFINITY:
  813. raise RuntimeError, "Generator point order is bad."
  814. if point.x() < 0 or n <= point.x() or point.y() < 0 or n <= point.y():
  815. raise RuntimeError, "Generator point has x or y out of range."
  816. def verifies( self, hash, signature ):
  817. G = self.generator
  818. n = G.order()
  819. r = signature.r
  820. s = signature.s
  821. if r < 1 or r > n-1: return False
  822. if s < 1 or s > n-1: return False
  823. c = inverse_mod( s, n )
  824. u1 = ( hash * c ) % n
  825. u2 = ( r * c ) % n
  826. xy = u1 * G + u2 * self.point
  827. v = xy.x() % n
  828. return v == r
  829. class Private_key( object ):
  830. def __init__( self, public_key, secret_multiplier ):
  831. self.public_key = public_key
  832. self.secret_multiplier = secret_multiplier
  833. def der( self ):
  834. hex_der_key = '06052b8104000a30740201010420' + \
  835. '%064x' % self.secret_multiplier + \
  836. 'a00706052b8104000aa14403420004' + \
  837. '%064x' % self.public_key.point.x() + \
  838. '%064x' % self.public_key.point.y()
  839. return hex_der_key.decode('hex')
  840. def sign( self, hash, random_k ):
  841. G = self.public_key.generator
  842. n = G.order()
  843. k = random_k % n
  844. p1 = k * G
  845. r = p1.x()
  846. if r == 0: raise RuntimeError, "amazingly unlucky random number r"
  847. s = ( inverse_mod( k, n ) * \
  848. ( hash + ( self.secret_multiplier * r ) % n ) ) % n
  849. if s == 0: raise RuntimeError, "amazingly unlucky random number s"
  850. return Signature( r, s )
  851. class EC_KEY(object):
  852. def __init__( self, secret ):
  853. curve = CurveFp( _p, _a, _b )
  854. generator = Point( curve, _Gx, _Gy, _r )
  855. self.pubkey = Public_key( generator, generator * secret )
  856. self.privkey = Private_key( self.pubkey, secret )
  857. self.secret = secret
  858. # end of python-ecdsa code
  859. # pywallet openssl private key implementation
  860. def i2d_ECPrivateKey(pkey, compressed=False):
  861. if compressed:
  862. key = '3081d30201010420' + \
  863. '%064x' % pkey.secret + \
  864. 'a081a53081a2020101302c06072a8648ce3d0101022100' + \
  865. '%064x' % _p + \
  866. '3006040100040107042102' + \
  867. '%064x' % _Gx + \
  868. '022100' + \
  869. '%064x' % _r + \
  870. '020101a124032200'
  871. else:
  872. key = '308201130201010420' + \
  873. '%064x' % pkey.secret + \
  874. 'a081a53081a2020101302c06072a8648ce3d0101022100' + \
  875. '%064x' % _p + \
  876. '3006040100040107044104' + \
  877. '%064x' % _Gx + \
  878. '%064x' % _Gy + \
  879. '022100' + \
  880. '%064x' % _r + \
  881. '020101a144034200'
  882. return key.decode('hex') + i2o_ECPublicKey(pkey, compressed)
  883. def i2o_ECPublicKey(pkey, compressed=False):
  884. # public keys are 65 bytes long (520 bits)
  885. # 0x04 + 32-byte X-coordinate + 32-byte Y-coordinate
  886. # 0x00 = point at infinity, 0x02 and 0x03 = compressed, 0x04 = uncompressed
  887. # compressed keys: <sign> <x> where <sign> is 0x02 if y is even and 0x03 if y is odd
  888. if compressed:
  889. if pkey.pubkey.point.y() & 1:
  890. key = '03' + '%064x' % pkey.pubkey.point.x()
  891. else:
  892. key = '02' + '%064x' % pkey.pubkey.point.x()
  893. else:
  894. key = '04' + \
  895. '%064x' % pkey.pubkey.point.x() + \
  896. '%064x' % pkey.pubkey.point.y()
  897. return key.decode('hex')
  898. # bitcointools hashes and base58 implementation
  899. def hash_160(public_key):
  900. md = hashlib.new('ripemd160')
  901. md.update(hashlib.sha256(public_key).digest())
  902. return md.digest()
  903. def public_key_to_bc_address(public_key):
  904. h160 = hash_160(public_key)
  905. return hash_160_to_bc_address(h160)
  906. def hash_160_to_bc_address(h160):
  907. vh160 = chr(addrtype) + h160
  908. h = Hash(vh160)
  909. addr = vh160 + h[0:4]
  910. return b58encode(addr)
  911. def bc_address_to_hash_160(addr):
  912. bytes = b58decode(addr, 25)
  913. return bytes[1:21]
  914. __b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
  915. __b58base = len(__b58chars)
  916. def b58encode(v):
  917. """ encode v, which is a string of bytes, to base58.
  918. """
  919. long_value = 0L
  920. for (i, c) in enumerate(v[::-1]):
  921. long_value += (256**i) * ord(c)
  922. result = ''
  923. while long_value >= __b58base:
  924. div, mod = divmod(long_value, __b58base)
  925. result = __b58chars[mod] + result
  926. long_value = div
  927. result = __b58chars[long_value] + result
  928. # Bitcoin does a little leading-zero-compression:
  929. # leading 0-bytes in the input become leading-1s
  930. nPad = 0
  931. for c in v:
  932. if c == '\0': nPad += 1
  933. else: break
  934. return (__b58chars[0]*nPad) + result
  935. def b58decode(v, length):
  936. """ decode v into a string of len bytes
  937. """
  938. long_value = 0L
  939. for (i, c) in enumerate(v[::-1]):
  940. long_value += __b58chars.find(c) * (__b58base**i)
  941. result = ''
  942. while long_value >= 256:
  943. div, mod = divmod(long_value, 256)
  944. result = chr(mod) + result
  945. long_value = div
  946. result = chr(long_value) + result
  947. nPad = 0
  948. for c in v:
  949. if c == __b58chars[0]: nPad += 1
  950. else: break
  951. result = chr(0)*nPad + result
  952. if length is not None and len(result) != length:
  953. return None
  954. return result
  955. # end of bitcointools base58 implementation
  956. # address handling code
  957. def Hash(data):
  958. return hashlib.sha256(hashlib.sha256(data).digest()).digest()
  959. def EncodeBase58Check(secret):
  960. hash = Hash(secret)
  961. return b58encode(secret + hash[0:4])
  962. def DecodeBase58Check(sec):
  963. vchRet = b58decode(sec, None)
  964. secret = vchRet[0:-4]
  965. csum = vchRet[-4:]
  966. hash = Hash(secret)
  967. cs32 = hash[0:4]
  968. if cs32 != csum:
  969. return None
  970. else:
  971. return secret
  972. def PrivKeyToSecret(privkey):
  973. if len(privkey) == 279:
  974. return privkey[9:9+32]
  975. else:
  976. return privkey[8:8+32]
  977. def SecretToASecret(secret, compressed=False):
  978. vchIn = chr((addrtype+128)&255) + secret
  979. if compressed: vchIn += '\01'
  980. return EncodeBase58Check(vchIn)
  981. def ASecretToSecret(sec):
  982. vch = DecodeBase58Check(sec)
  983. if vch and vch[0] == chr((addrtype+128)&255):
  984. return vch[1:]
  985. else:
  986. return False
  987. def regenerate_key(sec):
  988. b = ASecretToSecret(sec)
  989. if not b:
  990. return False
  991. b = b[0:32]
  992. secret = int('0x' + b.encode('hex'), 16)
  993. return EC_KEY(secret)
  994. def GetPubKey(pkey, compressed=False):
  995. return i2o_ECPublicKey(pkey, compressed)
  996. def GetPrivKey(pkey, compressed=False):
  997. return i2d_ECPrivateKey(pkey, compressed)
  998. def GetSecret(pkey):
  999. return ('%064x' % pkey.secret).decode('hex')
  1000. def is_compressed(sec):
  1001. b = ASecretToSecret(sec)
  1002. return len(b) == 33
  1003. # bitcointools wallet.dat handling code
  1004. def create_env(db_dir):
  1005. db_env = DBEnv(0)
  1006. r = db_env.open(db_dir, (DB_CREATE|DB_INIT_LOCK|DB_INIT_LOG|DB_INIT_MPOOL|DB_INIT_TXN|DB_THREAD|DB_RECOVER))
  1007. return db_env
  1008. def parse_CAddress(vds):
  1009. d = {'ip':'0.0.0.0','port':0,'nTime': 0}
  1010. try:
  1011. d['nVersion'] = vds.read_int32()
  1012. d['nTime'] = vds.read_uint32()
  1013. d['nServices'] = vds.read_uint64()
  1014. d['pchReserved'] = vds.read_bytes(12)
  1015. d['ip'] = socket.inet_ntoa(vds.read_bytes(4))
  1016. d['port'] = vds.read_uint16()
  1017. except:
  1018. pass
  1019. return d
  1020. def deserialize_CAddress(d):
  1021. return d['ip']+":"+str(d['port'])
  1022. def parse_BlockLocator(vds):
  1023. d = { 'hashes' : [] }
  1024. nHashes = vds.read_compact_size()
  1025. for i in xrange(nHashes):
  1026. d['hashes'].append(vds.read_bytes(32))
  1027. return d
  1028. def deserialize_BlockLocator(d):
  1029. result = "Block Locator top: "+d['hashes'][0][::-1].encode('hex_codec')
  1030. return result
  1031. def parse_setting(setting, vds):
  1032. if setting[0] == "f": # flag (boolean) settings
  1033. return str(vds.read_boolean())
  1034. elif setting[0:4] == "addr": # CAddress
  1035. d = parse_CAddress(vds)
  1036. return deserialize_CAddress(d)
  1037. elif setting == "nTransactionFee":
  1038. return vds.read_int64()
  1039. elif setting == "nLimitProcessors":
  1040. return vds.read_int32()
  1041. return 'unknown setting'
  1042. class SerializationError(Exception):
  1043. """ Thrown when there's a problem deserializing or serializing """
  1044. class BCDataStream(object):
  1045. def __init__(self):
  1046. self.input = None
  1047. self.read_cursor = 0
  1048. def clear(self):
  1049. self.input = None
  1050. self.read_cursor = 0
  1051. def write(self, bytes): # Initialize with string of bytes
  1052. if self.input is None:
  1053. self.input = bytes
  1054. else:
  1055. self.input += bytes
  1056. def map_file(self, file, start): # Initialize with bytes from file
  1057. self.input = mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ)
  1058. self.read_cursor = start
  1059. def seek_file(self, position):
  1060. self.read_cursor = position
  1061. def close_file(self):
  1062. self.input.close()
  1063. def read_string(self):
  1064. # Strings are encoded depending on length:
  1065. # 0 to 252 : 1-byte-length followed by bytes (if any)
  1066. # 253 to 65,535 : byte'253' 2-byte-length followed by bytes
  1067. # 65,536 to 4,294,967,295 : byte '254' 4-byte-length followed by bytes
  1068. # ... and the Bitcoin client is coded to understand:
  1069. # greater than 4,294,967,295 : byte '255' 8-byte-length followed by bytes of string
  1070. # ... but I don't think it actually handles any strings that big.
  1071. if self.input is None:
  1072. raise SerializationError("call write(bytes) before trying to deserialize")
  1073. try:
  1074. length = self.read_compact_size()
  1075. except IndexError:
  1076. raise SerializationError("attempt to read past end of buffer")
  1077. return self.read_bytes(length)
  1078. def write_string(self, string):
  1079. # Length-encoded as with read-string
  1080. self.write_compact_size(len(string))
  1081. self.write(string)
  1082. def read_bytes(self, length):
  1083. try:
  1084. result = self.input[self.read_cursor:self.read_cursor+length]
  1085. self.read_cursor += length
  1086. return result
  1087. except IndexError:
  1088. raise SerializationError("attempt to read past end of buffer")
  1089. return ''
  1090. def read_boolean(self): return self.read_bytes(1)[0] != chr(0)
  1091. def read_int16(self): return self._read_num('<h')
  1092. def read_uint16(self): return self._read_num('<H')
  1093. def read_int32(self): return self._read_num('<i')
  1094. def read_uint32(self): return self._read_num('<I')
  1095. def read_int64(self): return self._read_num('<q')
  1096. def read_uint64(self): return self._read_num('<Q')
  1097. def write_boolean(self, val): return self.write(chr(1) if val else chr(0))
  1098. def write_int16(self, val): return self._write_num('<h', val)
  1099. def write_uint16(self, val): return self._write_num('<H', val)
  1100. def write_int32(self, val): return self._write_num('<i', val)
  1101. def write_uint32(self, val): return self._write_num('<I', val)
  1102. def write_int64(self, val): return self._write_num('<q', val)
  1103. def write_uint64(self, val): return self._write_num('<Q', val)
  1104. def read_compact_size(self):
  1105. size = ord(self.input[self.read_cursor])
  1106. self.read_cursor += 1
  1107. if size == 253:
  1108. size = self._read_num('<H')
  1109. elif size == 254:
  1110. size = self._read_num('<I')
  1111. elif size == 255:
  1112. size = self._read_num('<Q')
  1113. return size
  1114. def write_compact_size(self, size):
  1115. if size < 0:
  1116. raise SerializationError("attempt to write size < 0")
  1117. elif size < 253:
  1118. self.write(chr(size))
  1119. elif size < 2**16:
  1120. self.write('\xfd')
  1121. self._write_num('<H', size)
  1122. elif size < 2**32:
  1123. self.write('\xfe')
  1124. self._write_num('<I', size)
  1125. elif size < 2**64:
  1126. self.write('\xff')
  1127. self._write_num('<Q', size)
  1128. def _read_num(self, format):
  1129. (i,) = struct.unpack_from(format, self.input, self.read_cursor)
  1130. self.read_cursor += struct.calcsize(format)
  1131. return i
  1132. def _write_num(self, format, num):
  1133. s = struct.pack(format, num)
  1134. self.write(s)
  1135. def open_wallet(db_env, db_file="wallet.dat", writable=False):
  1136. db = DB(db_env)
  1137. flags = DB_THREAD | (DB_CREATE if writable else DB_RDONLY)
  1138. try:
  1139. r = db.open(db_file, "main", DB_BTREE, flags)
  1140. except DBError:
  1141. r = True
  1142. if r is not None:
  1143. logging.error("Couldn't open " + db_file + "/main. Try quitting Bitcoin and running this again.")
  1144. sys.exit(1)
  1145. return db
  1146. def parse_wallet(db, item_callback):
  1147. kds = BCDataStream()
  1148. vds = BCDataStream()
  1149. for (key, value) in db.items():
  1150. d = { }
  1151. kds.clear(); kds.write(key)
  1152. vds.clear(); vds.write(value)
  1153. type = kds.read_string()
  1154. d["__key__"] = key
  1155. d["__value__"] = value
  1156. d["__type__"] = type
  1157. try:
  1158. if type == "tx":
  1159. d["tx_id"] = kds.read_bytes(32)
  1160. elif type == "name":
  1161. d['hash'] = kds.read_string()
  1162. d['name'] = vds.read_string()
  1163. elif type == "version":
  1164. d['version'] = vds.read_uint32()
  1165. elif type == "minversion":
  1166. d['minversion'] = vds.read_uint32()
  1167. elif type == "setting":
  1168. d['setting'] = kds.read_string()
  1169. d['value'] = parse_setting(d['setting'], vds)
  1170. elif type == "key":
  1171. d['public_key'] = kds.read_bytes(kds.read_compact_size())
  1172. d['private_key'] = vds.read_bytes(vds.read_compact_size())
  1173. elif type == "wkey":
  1174. d['public_key'] = kds.read_bytes(kds.read_compact_size())
  1175. d['private_key'] = vds.read_bytes(vds.read_compact_size())
  1176. d['created'] = vds.read_int64()
  1177. d['expires'] = vds.read_int64()
  1178. d['comment'] = vds.read_string()
  1179. elif type == "ckey":
  1180. d['public_key'] = kds.read_bytes(kds.read_compact_size())
  1181. d['crypted_key'] = vds.read_bytes(vds.read_compact_size())
  1182. elif type == "mkey":
  1183. d['nID'] = kds.read_int32()
  1184. d['crypted_key'] = vds.read_bytes(vds.read_compact_size())
  1185. d['salt'] = vds.read_bytes(vds.read_compact_size())
  1186. d['nDerivationMethod'] = vds.read_int32()
  1187. d['nDeriveIterations'] = vds.read_int32()
  1188. d['vchOtherDerivationParameters'] = vds.read_bytes(vds.read_compact_size())
  1189. elif type == "defaultkey":
  1190. d['key'] = vds.read_bytes(vds.read_compact_size())
  1191. elif type == "pool":
  1192. d['n'] = kds.read_int64()
  1193. d['nVersion'] = vds.read_int32()
  1194. d['nTime'] = vds.read_int64()
  1195. d['public_key'] = vds.read_bytes(vds.read_compact_size())
  1196. elif type == "acc":
  1197. d['account'] = kds.read_string()
  1198. d['nVersion'] = vds.read_int32()
  1199. d['public_key'] = vds.read_bytes(vds.read_compact_size())
  1200. elif type == "acentry":
  1201. d['account'] = kds.read_string()
  1202. d['n'] = kds.read_uint64()
  1203. d['nVersion'] = vds.read_int32()
  1204. d['nCreditDebit'] = vds.read_int64()
  1205. d['nTime'] = vds.read_int64()
  1206. d['otherAccount'] = vds.read_string()
  1207. d['comment'] = vds.read_string()
  1208. elif type == "bestblock":
  1209. d['nVersion'] = vds.read_int32()
  1210. d.update(parse_BlockLocator(vds))
  1211. item_callback(type, d)
  1212. except Exception, e:
  1213. traceback.print_exc()
  1214. print("ERROR parsing wallet.dat, type %s" % type)
  1215. print("key data in hex: %s"%key.encode('hex_codec'))
  1216. print("value data in hex: %s"%value.encode('hex_codec'))
  1217. sys.exit(1)
  1218. def update_wallet(db, type, data):
  1219. """Write a single item to the wallet.
  1220. db must be open with writable=True.
  1221. type and data are the type code and data dictionary as parse_wallet would
  1222. give to item_callback.
  1223. data's __key__, __value__ and __type__ are ignored; only the primary data
  1224. fields are used.
  1225. """
  1226. d = data
  1227. kds = BCDataStream()
  1228. vds = BCDataStream()
  1229. # Write the type code to the key
  1230. kds.write_string(type)
  1231. vds.write("") # Ensure there is something
  1232. try:
  1233. if type == "tx":
  1234. raise NotImplementedError("Writing items of type 'tx'")
  1235. kds.write(d['tx_id'])
  1236. elif type == "name":
  1237. kds.write_string(d['hash'])
  1238. vds.write_string(d['name'])
  1239. elif type == "version":
  1240. vds.write_uint32(d['version'])
  1241. elif type == "minversion":
  1242. vds.write_uint32(d['minversion'])
  1243. elif type == "setting":
  1244. raise NotImplementedError("Writing items of type 'setting'")
  1245. kds.write_string(d['setting'])
  1246. #d['value'] = parse_setting(d['setting'], vds)
  1247. elif type == "key":
  1248. kds.write_string(d['public_key'])
  1249. vds.write_string(d['private_key'])
  1250. elif type == "wkey":
  1251. kds.write_string(d['public_key'])
  1252. vds.write_string(d['private_key'])
  1253. vds.write_int64(d['created'])
  1254. vds.write_int64(d['expires'])
  1255. vds.write_string(d['comment'])
  1256. elif type == "ckey":
  1257. kds.write_string(d['public_key'])
  1258. vds.write_string(d['crypted_key'])
  1259. elif type == "defaultkey":
  1260. vds.write_string(d['key'])
  1261. elif type == "pool":
  1262. kds.write_int64(d['n'])
  1263. vds.write_int32(d['nVersion'])
  1264. vds.write_int64(d['nTime'])
  1265. vds.write_string(d['public_key'])
  1266. elif type == "acc":
  1267. kds.write_string(d['account'])
  1268. vds.write_int32(d['nVersion'])
  1269. vds.write_string(d['public_key'])
  1270. elif type == "acentry":
  1271. kds.write_string(d['account'])
  1272. kds.write_uint64(d['n'])
  1273. vds.write_int32(d['nVersion'])
  1274. vds.write_int64(d['nCreditDebit'])
  1275. vds.write_int64(d['nTime'])
  1276. vds.write_string(d['otherAccount'])
  1277. vds.write_string(d['comment'])
  1278. elif type == "bestblock":
  1279. vds.write_int32(d['nVersion'])
  1280. vds.write_compact_size(len(d['hashes']))
  1281. for h in d['hashes']:
  1282. vds.write(h)
  1283. else:
  1284. print "Unknown key type: "+type
  1285. # Write the key/value pair to the database
  1286. db.put(kds.input, vds.input)
  1287. except Exception, e:
  1288. print("ERROR writing to wallet.dat, type %s"%type)
  1289. print("data dictionary: %r"%data)
  1290. traceback.print_exc()
  1291. def read_wallet(json_db, db_env, db_file, print_wallet, print_wallet_transactions, transaction_filter):
  1292. db = open_wallet(db_env, db_file)
  1293. json_db['keys'] = []
  1294. json_db['pool'] = []
  1295. json_db['names'] = {}
  1296. def item_callback(type, d):
  1297. global password
  1298. if type == "name":
  1299. json_db['names'][d['hash']] = d['name']
  1300. elif type == "version":
  1301. json_db['version'] = d['version']
  1302. elif type == "minversion":
  1303. json_db['minversion'] = d['minversion']
  1304. elif type == "setting":
  1305. if not json_db.has_key('settings'): json_db['settings'] = {}
  1306. json_db["settings"][d['setting']] = d['value']
  1307. elif type == "defaultkey":
  1308. json_db['defaultkey'] = public_key_to_bc_address(d['key'])
  1309. elif type == "key":
  1310. addr = public_key_to_bc_address(d['public_key'])
  1311. compressed = d['public_key'][0] != '\04'
  1312. sec = SecretToASecret(PrivKeyToSecret(d['private_key']), compressed)
  1313. private_keys.append(sec)
  1314. json_db['keys'].append({'addr' : addr, 'sec' : sec})
  1315. # json_db['keys'].append({'addr' : addr, 'sec' : sec,
  1316. # 'secret':PrivKeyToSecret(d['private_key']).encode('hex'),
  1317. # 'pubkey':d['public_key'].encode('hex'),
  1318. # 'privkey':d['private_key'].encode('hex')})
  1319. elif type == "wkey":
  1320. if not json_db.has_key('wkey'): json_db['wkey'] = []
  1321. json_db['wkey']['created'] = d['created']
  1322. elif type == "ckey":
  1323. addr = public_key_to_bc_address(d['public_key'])
  1324. ckey = d['crypted_key']
  1325. pubkey = d['public_key']
  1326. json_db['keys'].append( {'addr' : addr, 'ckey': ckey.encode('hex'), 'pubkey': pubkey.encode('hex') })
  1327. elif type == "mkey":
  1328. mkey = {}
  1329. mkey['nID'] = d['nID']
  1330. mkey['crypted_key'] = d['crypted_key'].encode('hex')
  1331. mkey['salt'] = d['salt'].encode('hex')
  1332. mkey['nDeriveIterations'] = d['nDeriveIterations']
  1333. mkey['nDerivationMethod'] = d['nDerivationMethod']
  1334. mkey['vchOtherDerivationParameters'] = d['vchOtherDerivationParameters'].encode('hex')
  1335. json_db['mkey'] = mkey
  1336. if password == None and \
  1337. ('json' in opts or 'keysforaddrs' in opts or 'keys' in opts):
  1338. from mmgen.util import get_bitcoind_passphrase
  1339. password = get_bitcoind_passphrase("Enter password: ",opts)
  1340. if password != None:
  1341. global crypter
  1342. if crypter == 'pycrypto':
  1343. crypter = Crypter_pycrypto()
  1344. elif crypter == 'ssl':
  1345. crypter = Crypter_ssl()
  1346. else:
  1347. crypter = Crypter_pure()
  1348. logging.warning("pycrypto or libssl not found, decryption may be slow")
  1349. res = crypter.SetKeyFromPassphrase(password, d['salt'], d['nDeriveIterations'], d['nDerivationMethod'])
  1350. if res == 0:
  1351. logging.error("Unsupported derivation method")
  1352. sys.exit(1)
  1353. masterkey = crypter.Decrypt(d['crypted_key'])
  1354. crypter.SetKey(masterkey)
  1355. elif type == "pool":
  1356. json_db['pool'].append( {'n': d['n'], 'addr': public_key_to_bc_address(d['public_key']), 'nTime' : d['nTime'] } )
  1357. elif type == "acc":
  1358. json_db['acc'] = d['account']
  1359. # msg("Account %s (current key: %s)"%(d['account'], public_key_to_bc_address(d['public_key'])))
  1360. elif type == "acentry":
  1361. json_db['acentry'] = (d['account'], d['nCreditDebit'], d['otherAccount'], time.ctime(d['nTime']), d['n'], d['comment'])
  1362. elif type == "bestblock":
  1363. json_db['bestblock'] = d['hashes'][0][::-1].encode('hex_codec')
  1364. else:
  1365. json_db[type] = 'unsupported'
  1366. parse_wallet(db, item_callback)
  1367. db.close()
  1368. for k in json_db['keys']:
  1369. addr = k['addr']
  1370. if addr in json_db['names'].keys():
  1371. k["label"] = json_db['names'][addr]
  1372. else:
  1373. k["reserve"] = 1
  1374. if 'mkey' in json_db.keys() and password != None:
  1375. check = True
  1376. for k in json_db['keys']:
  1377. ckey = k['ckey'].decode('hex')
  1378. public_key = k['pubkey'].decode('hex')
  1379. crypter.SetIV(Hash(public_key))
  1380. secret = crypter.Decrypt(ckey)
  1381. compressed = public_key[0] != '\04'
  1382. if check:
  1383. check = False
  1384. pkey = EC_KEY(int('0x' + secret.encode('hex'), 16))
  1385. if public_key != GetPubKey(pkey, compressed):
  1386. logging.error("wrong password")
  1387. sys.exit(1)
  1388. sec = SecretToASecret(secret, compressed)
  1389. k['sec'] = sec
  1390. k['secret'] = secret.encode('hex')
  1391. del(k['ckey'])
  1392. del(k['secret'])
  1393. del(k['pubkey'])
  1394. private_keys.append(sec)
  1395. del(json_db['pool'])
  1396. del(json_db['names'])
  1397. # Non-portable. For Windows, works only if supplied filename is in current dir
  1398. # main()
  1399. import os.path
  1400. infile = os.path.abspath(cmd_args[0])
  1401. db_dir,db_file = os.path.dirname(infile),os.path.basename(infile)
  1402. # print "[%s] [%s]" % (db_dir,db_file)
  1403. db_env = create_env(db_dir)
  1404. read_wallet(json_db, db_env, db_file, True, True, "")
  1405. if json_db.get('minversion') > max_version:
  1406. print "Version mismatch (must be <= %d)" % max_version
  1407. exit(1)
  1408. wallet_addrs = [i['addr'] for i in json_db['keys']]
  1409. if 'json' in opts:
  1410. data = [json.dumps(json_db, sort_keys=True, indent=4)]
  1411. ext,what = "json","json dump"
  1412. elif 'keys' in opts:
  1413. data = sorted([i['sec'] for i in json_db['keys']])
  1414. ext,what = "keys","private keys"
  1415. elif 'addrs' in opts:
  1416. data = sorted([i['addr'] for i in json_db['keys']])
  1417. ext,what = "addrs","addresses"
  1418. elif 'keysforaddrs' in opts:
  1419. from mmgen.util import get_lines_from_file
  1420. usr_addrs = set(get_lines_from_file(opts['keysforaddrs'],"addresses",remove_comments=True))
  1421. data = [i['sec'] for i in json_db['keys'] if i['addr'] in usr_addrs]
  1422. ext,what = "keys","private keys"
  1423. if len(data) < len(usr_addrs):
  1424. msg("Warning: not all requested keys found")
  1425. len_arg = "%s" % len(wallet_addrs) \
  1426. if len(data) == len(wallet_addrs) or ext == "json" \
  1427. else "%s:%s" % (len(data),len(wallet_addrs))
  1428. from mmgen.util import make_chksum_8,write_walletdat_dump_to_file,write_to_stdout
  1429. wallet_id = make_chksum_8(str(sorted(wallet_addrs)))
  1430. data = "\n".join(data) + "\n"
  1431. # Output data
  1432. if 'stdout' in opts:
  1433. confirm = False if 'addrs' in opts else True
  1434. write_to_stdout(data,"secret keys",confirm)
  1435. elif not sys.stdout.isatty():
  1436. write_to_stdout(data,"secret keys",confirm=False)
  1437. else:
  1438. write_walletdat_dump_to_file(wallet_id, data, len_arg, ext, what, opts)