def solve(x):
cry = x
clear = base58.b58decode(cry)
li = list()
for i in clear:
li.append(ord(i))
ori = clear[:-4]
#chk = clear[-4:]
rechk = hashlib.sha256(ori).digest()
rechk = hashlib.sha256(rechk).digest()
#a = list()
#for i in rechk:
# a.append(ord(i))
checksum = rechk[:4]
final = ori+checksum
return base58.b58encode(final)
python类b58decode()的实例源码
def reissueAsset(self, Asset, quantity, reissuable=False, txFee=pywaves.DEFAULT_TX_FEE):
timestamp = int(time.time() * 1000)
sData = b'\5' + \
base58.b58decode(self.publicKey) + \
base58.b58decode(Asset.assetId) + \
struct.pack(">Q", quantity) + \
(b'\1' if reissuable else b'\0') + \
struct.pack(">Q",txFee) + \
struct.pack(">Q", timestamp)
signature = crypto.sign(self.privateKey, sData)
data = json.dumps({
"senderPublicKey": self.publicKey,
"assetId": Asset.assetId,
"quantity": quantity,
"timestamp": timestamp,
"reissuable": reissuable,
"fee": txFee,
"signature": signature
})
req = pywaves.wrapper('/assets/broadcast/reissue', data)
if pywaves.OFFLINE:
return req
else:
return req.get('id', 'ERROR')
def burnAsset(self, Asset, quantity, txFee=pywaves.DEFAULT_TX_FEE):
timestamp = int(time.time() * 1000)
sData = '\6' + \
base58.b58decode(self.publicKey) + \
base58.b58decode(Asset.assetId) + \
struct.pack(">Q", quantity) + \
struct.pack(">Q", txFee) + \
struct.pack(">Q", timestamp)
signature = crypto.sign(self.privateKey, sData)
data = json.dumps({
"senderPublicKey": self.publicKey,
"assetId": Asset.assetId,
"quantity": quantity,
"timestamp": timestamp,
"fee": txFee,
"signature": signature
})
req = pywaves.wrapper('/assets/broadcast/burn', data)
if pywaves.OFFLINE:
return req
else:
return req.get('id', 'ERROR')
def cancelOrder(self, assetPair, order):
if not pywaves.OFFLINE:
if order.status() == 'Filled':
logging.error("Order already filled")
elif not order.status():
logging.error("Order not found")
sData = base58.b58decode(self.publicKey) + \
base58.b58decode(order.orderId)
signature = crypto.sign(self.privateKey, sData)
data = json.dumps({
"sender": self.publicKey,
"orderId": order.orderId,
"signature": signature
})
req = pywaves.wrapper('/matcher/orderbook/%s/%s/cancel' % ('WAVES' if assetPair.asset1.assetId=='' else assetPair.asset1.assetId, 'WAVES' if assetPair.asset2.assetId=='' else assetPair.asset2.assetId), data, host=pywaves.MATCHER)
if pywaves.OFFLINE:
return req
else:
id = -1
if req['status'] == 'OrderCanceled':
id = req['orderId']
logging.info('Order Cancelled - ID: %s' % id)
return id
def cancelOrderByID(self, assetPair, orderId):
sData = base58.b58decode(self.publicKey) + \
base58.b58decode(orderId)
signature = crypto.sign(self.privateKey, sData)
data = json.dumps({
"sender": self.publicKey,
"orderId": orderId,
"signature": signature
})
req = pywaves.wrapper('/matcher/orderbook/%s/%s/cancel' % ('WAVES' if assetPair.asset1.assetId=='' else assetPair.asset1.assetId, 'WAVES' if assetPair.asset2.assetId=='' else assetPair.asset2.assetId), data, host=pywaves.MATCHER)
if pywaves.OFFLINE:
return req
else:
id = -1
if req['status'] == 'OrderCanceled':
id = req['orderId']
logging.info('Order Cancelled - ID: %s' % id)
return id
def createAlias(self, alias, txFee=pywaves.DEFAULT_ALIAS_FEE, timestamp=0):
aliasWithNetwork = b'\x02' + str(pywaves.CHAIN_ID) + struct.pack(">H", len(alias)) + crypto.str2bytes(alias)
if not self.privateKey:
logging.error('Private key required')
else:
if timestamp == 0:
timestamp = int(time.time() * 1000)
sData = b'\x0a' + \
base58.b58decode(self.publicKey) + \
struct.pack(">H", len(aliasWithNetwork)) + \
crypto.str2bytes(aliasWithNetwork) + \
struct.pack(">Q", txFee) + \
struct.pack(">Q", timestamp)
signature = crypto.sign(self.privateKey, sData)
data = json.dumps({
"alias": alias,
"senderPublicKey": self.publicKey,
"fee": txFee,
"timestamp": timestamp,
"signature": signature
})
return pywaves.wrapper('/alias/broadcast/create', data)
def multihash_ref(ref):
if isinstance(ref, MultihashReference):
return ref
try:
ref = ref.reference
except AttributeError:
pass
try:
ref = ref['@link']
except (TypeError, KeyError):
pass
try:
ref = base58.b58decode(ref)
except ValueError:
pass
return MultihashReference(multihash=ref)
def ToScriptHash(self, address):
"""
Retrieve the script_hash based from an address.
Args:
address (str): a base58 encoded address.
Raises:
ValuesError: if an invalid address is supplied or the coin version is incorrect.
Exception: if the address checksum fails.
Returns:
UInt160: script hash.
"""
data = b58decode(address)
if len(data) != 25:
raise ValueError('Not correct Address, wrong length.')
if data[0] != self.AddressVersion:
raise ValueError('Not correct Coin Version')
checksum = Crypto.Default().Hash256(data[:21])[:4]
if checksum != data[21:]:
raise Exception('Address format error')
return UInt160(data=data[1:21])
def _fulfillment_from_details(data, _depth=0):
"""Load a fulfillment for a signing spec dictionary
Args:
data: tx.output[].condition.details dictionary
"""
if _depth == 100:
raise ThresholdTooDeep()
if data['type'] == 'ed25519-sha-256':
public_key = base58.b58decode(data['public_key'])
return Ed25519Sha256(public_key=public_key)
if data['type'] == 'threshold-sha-256':
threshold = ThresholdSha256(data['threshold'])
for cond in data['subconditions']:
cond = _fulfillment_from_details(cond, _depth+1)
threshold.add_subfulfillment(cond)
return threshold
raise UnsupportedTypeError(data.get('type'))
def btc_addr_to_hash_160(btc_addr):
""" Calculates the RIPEMD-160 hash from a given Bitcoin address
:param btc_addr: Bitcoin address.
:type btc_addr: str
:return: The corresponding RIPEMD-160 hash.
:rtype: hex str
"""
# Base 58 decode the Bitcoin address.
decoded_addr = b58decode(btc_addr)
# Covert the address from bytes to hex.
decoded_addr_hex = hexlify(decoded_addr)
# Obtain the RIPEMD-160 hash by removing the first and four last bytes of the decoded address, corresponding to
# the network version and the checksum of the address.
h160 = decoded_addr_hex[2:-8]
return h160
def get(self, address=None):
if address is None:
raise HTTPError(400, reason="No address")
try:
from_height = long(self.get_argument("from_height", 0))
except:
raise HTTPError(400)
address_decoded = base58.b58decode(address)
address_version = address_decoded[0]
address_hash = address_decoded[1:21]
request = {
"id": random_id_number(),
"command":"fetch_history",
"params": [address_version, address_hash, from_height]
}
self.application._obelisk_handler.handle_request(self, request)
def parse_dict(self, data):
"""
Generate fulfillment payload from a dict
Args:
data (dict): description of the fulfillment
Returns:
Fulfillment
"""
self.public_key = base58.b58decode(data['public_key'])
if data['signature']:
self.signature = base58.b58decode(data['signature'])
# TODO Adapt according to outcomes of
# https://github.com/rfcs/crypto-conditions/issues/16
def sendAsset(pubKey, privKey, recipient, assetId, amount, txfee):
timestamp = int(time.time() * 1000)
sData = '\4' + base58.b58decode(pubKey) + '\1' + base58.b58decode(assetId) + '\0' + struct.pack(">Q", timestamp) + struct.pack(">Q", amount) + struct.pack(">Q", txfee) + base58.b58decode(recipient) + '\0\0'
random64 = os.urandom(64)
signature = base58.b58encode(curve.calculateSignature(random64, base58.b58decode(privKey), sData))
data = json.dumps({
"assetId": assetId,
"senderPublicKey": pubKey,
"recipient": recipient,
"amount": amount,
"fee": txfee,
"timestamp": timestamp,
"attachment": "",
"signature": signature
})
c = pycurl.Curl()
c.setopt(pycurl.URL, "http://%s:%s/assets/broadcast/transfer" % (NODE_IP, NODE_PORT))
c.setopt(pycurl.HTTPHEADER, ['Content-Type: application/json', 'Accept: application/json'])
c.setopt(pycurl.POST, 1)
c.setopt(pycurl.POSTFIELDS, data)
c.perform()
c.close()
def commit(self, txnCount, stateRoot, txnRoot) -> List:
"""
:param txnCount: The number of requests to commit (The actual requests
are picked up from the uncommitted list from the ledger)
:param stateRoot: The state trie root after the txns are committed
:param txnRoot: The txn merkle root after the txns are committed
:return: list of committed transactions
"""
(seqNoStart, seqNoEnd), committedTxns = \
self.ledger.commitTxns(txnCount)
stateRoot = base58.b58decode(stateRoot.encode())
# Probably the following assertion fail should trigger catchup
assert self.ledger.root_hash == txnRoot, '{} {}'.format(
self.ledger.root_hash, txnRoot)
self.state.commit(rootHash=stateRoot)
return txnsWithSeqNo(seqNoStart, seqNoEnd, committedTxns)
def solve(x):
base58char = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
for i in range(len(x)):
for char in base58char:
cry = x[:i]+char+x[i+1:]
print cry
clear = base58.b58decode(str(cry))
ori = clear[:-4]
chk = clear[-4:]
rechk = hashlib.sha256(hashlib.sha256(ori).digest()).digest()
if chk == rechk[:4]: return cry
for i in range(len(x)):
for j in range(len(x)):
if i == j: continue
for charI in base58char:
for charJ in base58char:
cry = x[:i]+charI+x[i+1:]
cry = cry[:j]+charJ+cry[j+1:]
print cry
clear = base58.b58decode(str(cry))
ori = clear[:-4]
chk = clear[-4:]
rechk = hashlib.sha256(hashlib.sha256(ori).digest()).digest()
if chk == rechk[:4]: return cry
'''
clear = base58.b58decode(str(cry))
#li = list()
#for i in clear:
# li.append(ord(i))
ori = clear[:-4]
chk = clear[-4:]
rechk = hashlib.sha256(hashlib.sha256(ori).digest()).digest()
checksum = rechk[:4]
final = ori+checksum
return base58.b58encode(final)
'''
#print solve(cry)
#print solve('15GJF8Do1NDSMy4eV8H82dfFtTvKaqYyhg')
def b58hex(b58):
try:
return base58.b58decode(b58, None).encode('hex_codec')
except Exception:
raise PageNotFound()
def shortlink_block(link):
try:
data = base58.b58decode(link, None)
except Exception:
raise PageNotFound()
return ('00' * ord(data[0])) + data[1:].encode('hex_codec')
def decode_address(addr):
bytes = base58.b58decode(addr, None)
if len(bytes) < 25:
bytes = ('\0' * (25 - len(bytes))) + bytes
return bytes[:-24], bytes[-24:-4]
def b58hex(b58):
try:
return base58.b58decode(b58, None).encode('hex_codec')
except Exception:
raise PageNotFound()
def shortlink_block(link):
try:
data = base58.b58decode(link, None)
except Exception:
raise PageNotFound()
return ('00' * ord(data[0])) + data[1:].encode('hex_codec')
def _generate(self, privateKey='', seed=''):
self.seed = seed
if not privateKey and not seed:
wordCount = 2048
words = []
for i in range(5):
r = crypto.bytes2str(os.urandom(4))
x = (ord(r[3])) + (ord(r[2]) << 8) + (ord(r[1]) << 16) + (ord(r[0]) << 24)
w1 = x % wordCount
w2 = ((int(x / wordCount) >> 0) + w1) % wordCount
w3 = ((int((int(x / wordCount) >> 0) / wordCount) >> 0) + w2) % wordCount
words.append(wordList[w1])
words.append(wordList[w2])
words.append(wordList[w3])
self.seed = ' '.join(words)
seedHash = crypto.hashChain(('\0\0\0\0' + self.seed).encode('utf-8'))
accountSeedHash = crypto.sha256(seedHash)
if not privateKey:
privKey = curve.generatePrivateKey(accountSeedHash)
else:
privKey = base58.b58decode(privateKey)
pubKey = curve.generatePublicKey(privKey)
unhashedAddress = chr(1) + str(pywaves.CHAIN_ID) + crypto.hashChain(pubKey)[0:20]
addressHash = crypto.hashChain(crypto.str2bytes(unhashedAddress))[0:4]
self.address = base58.b58encode(crypto.str2bytes(unhashedAddress + addressHash))
self.publicKey = base58.b58encode(pubKey)
self.privateKey = base58.b58encode(privKey)
def issueAsset(self, name, description, quantity, decimals=0, reissuable=False, txFee=pywaves.DEFAULT_ASSET_FEE):
if not self.privateKey:
logging.error('Private key required')
elif len(name) < 4 or len(name) > 16:
logging.error('Asset name must be between 4 and 16 characters long')
else:
timestamp = int(time.time() * 1000)
sData = b'\3' + \
base58.b58decode(self.publicKey) + \
struct.pack(">H", len(name)) + \
crypto.str2bytes(name) + \
struct.pack(">H", len(description)) + \
crypto.str2bytes(description) + \
struct.pack(">Q", quantity) + \
struct.pack(">B", decimals) + \
(b'\1' if reissuable else b'\0') + \
struct.pack(">Q", txFee) + \
struct.pack(">Q", timestamp)
signature=crypto.sign(self.privateKey, sData)
data = json.dumps({
"senderPublicKey": self.publicKey,
"name": name,
"quantity": quantity,
"timestamp": timestamp,
"description": description,
"decimals": decimals,
"reissuable": reissuable,
"fee": txFee,
"signature": signature
})
req = pywaves.wrapper('/assets/broadcast/issue', data)
if pywaves.OFFLINE:
return req
else:
return pywaves.Asset(req['assetId'])
def sendWaves(self, recipient, amount, attachment='', txFee=pywaves.DEFAULT_TX_FEE, timestamp=0):
if not self.privateKey:
logging.error('Private key required')
elif amount <= 0:
logging.error('Amount must be > 0')
elif not pywaves.OFFLINE and self.balance() < amount + txFee:
logging.error('Insufficient Waves balance')
else:
if timestamp == 0:
timestamp = int(time.time() * 1000)
sData = b'\4' + \
base58.b58decode(self.publicKey) + \
b'\0\0' + \
struct.pack(">Q", timestamp) + \
struct.pack(">Q", amount) + \
struct.pack(">Q", txFee) + \
base58.b58decode(recipient.address) + \
struct.pack(">H", len(attachment)) + \
crypto.str2bytes(attachment)
signature = crypto.sign(self.privateKey, sData)
data = json.dumps({
"senderPublicKey": self.publicKey,
"recipient": recipient.address,
"amount": amount,
"fee": txFee,
"timestamp": timestamp,
"attachment": base58.b58encode(crypto.str2bytes(attachment)),
"signature": signature
})
return pywaves.wrapper('/assets/broadcast/transfer', data)
def lease(self, recipient, amount, txFee=pywaves.DEFAULT_LEASE_FEE, timestamp=0):
if not self.privateKey:
logging.error('Private key required')
elif amount <= 0:
logging.error('Amount must be > 0')
elif not pywaves.OFFLINE and self.balance() < amount + txFee:
logging.error('Insufficient Waves balance')
else:
if timestamp == 0:
timestamp = int(time.time() * 1000)
sData = b'\x08' + \
base58.b58decode(self.publicKey) + \
base58.b58decode(recipient.address) + \
struct.pack(">Q", amount) + \
struct.pack(">Q", txFee) + \
struct.pack(">Q", timestamp)
signature = crypto.sign(self.privateKey, sData)
data = json.dumps({
"senderPublicKey": self.publicKey,
"recipient": recipient.address,
"amount": amount,
"fee": txFee,
"timestamp": timestamp,
"signature": signature
})
req = pywaves.wrapper('/leasing/broadcast/lease', data)
if pywaves.OFFLINE:
return req
else:
return req['id']
def leaseCancel(self, leaseId, txFee=pywaves.DEFAULT_LEASE_FEE, timestamp=0):
if not self.privateKey:
logging.error('Private key required')
elif not pywaves.OFFLINE and self.balance() < txFee:
logging.error('Insufficient Waves balance')
else:
if timestamp == 0:
timestamp = int(time.time() * 1000)
sData = b'\x09' + \
base58.b58decode(self.publicKey) + \
struct.pack(">Q", txFee) + \
struct.pack(">Q", timestamp) + \
base58.b58decode(leaseId)
signature = crypto.sign(self.privateKey, sData)
data = json.dumps({
"senderPublicKey": self.publicKey,
"txId": leaseId,
"fee": txFee,
"timestamp": timestamp,
"signature": signature
})
req = pywaves.wrapper('/leasing/broadcast/cancel', data)
if pywaves.OFFLINE:
return req
elif 'leaseId' in req:
return req['leaseId']
def cancelOpenOrders(self, assetPair):
orders = self.getOrderHistory(assetPair)
for order in orders:
status = order['status']
orderId = order['id']
if status=='Accepted' or status=='PartiallyFilled':
sData = base58.b58decode(self.publicKey) + \
base58.b58decode(orderId)
signature = crypto.sign(self.privateKey, sData)
data = json.dumps({
"sender": self.publicKey,
"orderId": orderId,
"signature": signature
})
pywaves.wrapper('/matcher/orderbook/%s/%s/cancel' % ('WAVES' if assetPair.asset1.assetId == '' else assetPair.asset1.assetId, 'WAVES' if assetPair.asset2.assetId == '' else assetPair.asset2.assetId), data, host=pywaves.MATCHER)
def deleteOrderHistory(self, assetPair):
orders = self.getOrderHistory(assetPair)
for order in orders:
orderId = order['id']
sData = base58.b58decode(self.publicKey) + \
base58.b58decode(orderId)
signature = crypto.sign(self.privateKey, sData)
data = json.dumps({
"sender": self.publicKey,
"orderId": orderId,
"signature": signature
})
pywaves.wrapper('/matcher/orderbook/%s/%s/delete' % ('WAVES' if assetPair.asset1.assetId == '' else assetPair.asset1.assetId, 'WAVES' if assetPair.asset2.assetId == '' else assetPair.asset2.assetId), data, host=pywaves.MATCHER)
def sign(privateKey, message):
random64 = os.urandom(64)
return base58.b58encode(curve.calculateSignature(random64, base58.b58decode(privateKey), message))
def simpleDecrypt(self, passphrase, base58_data):
"""Decrypt data.
Args:
passphrase (str): passphrase to use for decryption.
base58_data (str/bytes): base58-encoded encrypted data.
Returns:
(str): original data.
"""
key, iv = self.EVP_BytesToKey(passphrase, 32, 16)
return self.decrypt(base58.b58decode(base58_data), key, iv)
def ascii2bytes(s):
"""
>>> ascii2bytes('3yZe7d')
b'test'
"""
return b58decode(s)