【发布时间】:2017-08-22 20:26:00
【问题描述】:
我试图从这个网站复制python程序:http://ecomunsing.com/build-your-own-blockchain。
Python程序如下:
import hashlib, json
import random
def hashMe(msg=''):
if type(msg)!=str:
msg = json.dumps(msg, sort_keys=True)
return str(hashlib.sha256(msg).hexdigest(), 'uft-8')
def makeTransaction(maxValue=3):
sign= int(random.getrandbits(1))*2-1
amount = random.randint(1,maxValue)
alicePays = sign*amount
bobPays = -1*alicePays
return {u'Alice':alicePays, u'Bob':bobPays}
txnBuffer = [makeTransaction() for i in range(30)]
def updateState(txn, state):
state = state.copy()
for key in txn:
if key in state.key():
state[key] += txn[key]
else:
state[key] = txn[key]
return state
def isValidTxn(txn, state):
if sum(txn.values()) is not 0:
return False
for key in txn.keys():
acctBalance = state[key]
else:
acctBalance = 0
if (acctBalance + txn[key]) <0:
return False
return True
state = {u'Alice':50, u'Bob':50}
genesisBlockTxns = [state]
genesisBlockContents = {u'blockNumber':0,u'parentHash':None,u'txnCount':1,u'txns':genesisBlockTxns}
genesisHash = hashMe( genesisBlockContents )
错误信息是
File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
execfile(filename, namespace)
File "C:\ProgramData\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/simpleexample.py", line 186, in <module>
genesisHash = hashMe( genesisBlockContents )
File "C:/simpleexample.py", line 45, in hashMe
return str(hashlib.sha256(msg).hexdigest(), 'uft-8')
TypeError: Unicode-objects must be encoded before hashing
我正在使用 Python 3.6.0 | Windows 7 中的 Anaconda 4.3.1(32 位)。请帮助并提前致谢。
【问题讨论】:
-
欢迎来到 Stack Overflow。请阅读stackoverlow.com/help/how-to-ask 以获取有关如何提问的指导
标签: python unicode hash encode