mmgen-pywallet 52 KB

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