def __init__(self, blockchain=None, name: str = 'block', height: int = 0, version: int = 0, coinbase: Corner = None, corners: list = None, timestamp=0, previous_hash=pycryptonight.cn_slow_hash(b''), nonce=(0).to_bytes(NONCE_SIZE, 'big')): """ Initialises a Block instance. :param blockchain: Blockchain :param name: str :param height: int :param version: int :param coinbase: Corner :param corners: Corner list :param timestamp: int :param previous_hash: bytes :param nonce: bytes """ super().__init__(f"{name} - {height} :") self.blockchain = blockchain self.version = version self.timestamp = timestamp self.previous_hash = previous_hash self.nonce = nonce self.coinbase = coinbase self._corners = [] if corners is None else corners self.merkle_tree = MerkleTree(self.corners, fast_hash) self.hash = self.get_hash() self.difficulty = 4
def generate_key(data): """ Chacha key derivation used in Monero :param data: :return: """ return pycryptonight.cn_slow_hash(data)
def __init__(self, parent=None, last_hash=pycryptonight.cn_slow_hash(b''), nonce=0): super().__init__(parent) self.last_hash = last_hash self.nonce = nonce
def calc_sha256(self): if self.sha256 is None: r = b"" r += struct.pack("<i", self.nVersion) r += ser_uint256(self.hashPrevBlock) r += ser_uint256(self.hashMerkleRoot) r += struct.pack("<I", self.nTime) r += struct.pack("<I", self.nBits) r += struct.pack("<I", self.nNonce) # For kevacoin, self.sha256 doesn't actually store the sha256 value. # It stores the cn_fast hash instead. self.sha256_actual = uint256_from_str(hash256(r)) #self.hash = encode(hash256(r)[::-1], 'hex_codec').decode('ascii') # Cryptonote cn hash c = b"" c += struct.pack("<B", self.major_version) c += struct.pack("<B", self.minor_version) c += ser_varint(self.timestamp) # prev_id is used to store sha256 value of the blockhash for Proof-of-Work self.prev_id = self.sha256_actual c += ser_uint256(self.prev_id) c += struct.pack("<I", self.nonce) c += ser_uint256(self.merkle_root) c += struct.pack("<B", self.nTxes) # self.sha256 stores the cn_fast hash. cn_hash = pycryptonight.cn_fast_hash(c) self.sha256 = uint256_from_str(cn_hash) self.hash = encode(cn_hash[::-1], 'hex_codec').decode('ascii') # nNonce is used to store block height. self.scrypt256 = uint256_from_str(pycryptonight.cn_slow_hash(c, self.major_version - 6, 0, self.nNonce))
def worker(q, s): started = time.time() hash_count = 0 while 1: job = q.get() if job.get('login_id'): login_id = job.get('login_id') print('Login ID: {}'.format(login_id)) blob = job.get('blob') target = job.get('target') job_id = job.get('job_id') height = job.get('height') block_major = int(blob[:2], 16) cnv = 0 if block_major >= 7: cnv = block_major - 6 if cnv > 5: seed_hash = binascii.unhexlify(job.get('seed_hash')) print('New job with target: {}, RandomX, height: {}'.format(target, height)) else: print('New job with target: {}, CNv{}, height: {}'.format(target, cnv, height)) target = struct.unpack('I', binascii.unhexlify(target))[0] if target >> 32 == 0: target = int(0xFFFFFFFFFFFFFFFF / int(0xFFFFFFFF / target)) nonce = 1 while 1: bin = pack_nonce(blob, nonce) if cnv > 5: hash = pyrx.get_rx_hash(bin, seed_hash, height) else: hash = pycryptonight.cn_slow_hash(bin, cnv, 0, height) hash_count += 1 sys.stdout.write('.') sys.stdout.flush() hex_hash = binascii.hexlify(hash).decode() r64 = struct.unpack('Q', hash[24:])[0] if r64 < target: elapsed = time.time() - started hr = int(hash_count / elapsed) print('{}Hashrate: {} H/s'.format(os.linesep, hr)) if nicehash: nonce = struct.unpack('I', bin[39:43])[0] submit = { 'method':'submit', 'params': { 'id': login_id, 'job_id': job_id, 'nonce': binascii.hexlify(struct.pack('<I', nonce)).decode(), 'result': hex_hash }, 'id':1 } print('Submitting hash: {}'.format(hex_hash)) s.sendall(str(json.dumps(submit)+'\n').encode('utf-8')) select.select([s], [], [], 3) if not q.empty(): break nonce += 1
def get_hash(self): """ Calculates the block's hash. :return: bytes """ self.hash = pycryptonight.cn_slow_hash(self.header, 4) return self.hash
def main(): write("%s -> %s" % (original, hashed)) randomed = os.urandom(2000) result = pycryptonight.cn_slow_hash(randomed, 1).encode("hex") write(randomed.encode("hex") + "?") answer = sys.stdin.readline().strip() if answer == result: write("Flag: %s" % flag.flag) else: write("No.")
def main(): p = remote("ctf.pwn.sg", 1502) question = p.recvline_contains("?") question = question.replace("?", "").strip() log.info("Got question: %s" % question) question = question.decode("hex") result = pycryptonight.cn_slow_hash(question, 1).encode("hex") log.info("Replying with %s" % result) p.sendline(result) flag = p.recvline() log.success(flag)
def __init__(self, blockchain=None, name='block', height=0, version=0, coinbase=None, corners=None, timestamp=0, previous_hash=pycryptonight.cn_slow_hash(b''), nonce=(0).to_bytes(NONCE_SIZE, 'big')): super().__init__(f"{name} - {height} :") self.blockchain = blockchain self.version = version self.timestamp = timestamp self.previous_hash = previous_hash self.nonce = nonce self.coinbase = coinbase self._corners = [] if corners is None else corners self.merkle_tree = MerkleTree(self.corners, fast_hash) self.hash = self.get_hash() self.difficulty = 4
#!/usr/bin/python import binascii import pycryptonight # Paste the input from nc ctf.pwn.sg 1502 inp = b'...' h = pycryptonight.cn_slow_hash(binascii.unhexlify(inp), 1) print binascii.hexlify(h)
def main(): base_diff = 2**256 - 1 payload = { 'jsonrpc': '2.0', 'id': '0', 'method': 'get_block_template', 'params': { 'wallet_address': wallet_address } } print('Fetching block template') req = requests.post(rpc_url, json=payload) result = req.json().get('result') bhb = result.get('blockhashing_blob') btb = result.get('blocktemplate_blob') diff = result.get('difficulty') print('Target difficulty: {}'.format(diff)) height = result.get('height') block_major = int(btb[:2], 16) cnv = 0 if block_major >= 7: cnv = block_major - 6 if cnv > 5: seed_hash = binascii.unhexlify(result.get('seed_hash')) nonce = 1 hash_count = 0 started = time.time() print('Mining for a valid hash') try: while 1: bin = pack_nonce(bhb, nonce) if cnv > 5: hash = pyrx.get_rx_hash(bin, seed_hash, height) else: hash = pycryptonight.cn_slow_hash(bin, cnv, 0, height) hash_count += 1 sys.stdout.write('.') sys.stdout.flush() hex_hash = binascii.hexlify(hash) if base_diff / int(hex_hash, 16) >= diff: break else: nonce += 1 except KeyboardInterrupt: print('{}Aborting'.format(os.linesep)) sys.exit(-1) elapsed = time.time() - started hr = int(hash_count / elapsed) print('{}Hashrate: {} H/s'.format(os.linesep, hr)) print('Found a valid hash: {}'.format(hex_hash.decode())) btb = binascii.hexlify(pack_nonce(btb, nonce)) payload = { 'jsonrpc': '2.0', 'id': '0', 'method': 'submit_block', 'params': [btb] } print('Submitting block') print(payload) req = requests.post(rpc_url, json=payload) result = req.json() print(result)
process output of: nc ctf.pwn.sg 1502 """ import string import binascii import pycryptonight FILENAME = 'out.txt' clues = [] with open(FILENAME, 'r') as f: clues = f.readline().rstrip().split(' ') clues.append(f.readline().rstrip()[:-1]) # clues[0] --> length of 86 byte_string = bytes.fromhex(clues[0]) res_byte_string = pycryptonight.cn_slow_hash(byte_string, variant = 1) res_hex_string = binascii.hexlify(res_byte_string) if res_hex_string.decode('utf-8') == clues[2]: print(">> found the right hash algorithm!") else: print(">> wrong hash algorithm")
def test_slow2(self): self.tst_method('tests-slow-2.txt', lambda x, y: pycryptonight.cn_slow_hash(x, 2, 0, 0))
def get_hash(self): self.hash = pycryptonight.cn_slow_hash(self.header, 4) return self.hash
from pwn import * import binascii import pycryptonight import pdb HOST = 'ctf.pwn.sg' PORT = 1502 conn = remote(HOST, PORT) clues = str(conn.recvline().rstrip()).split(' ') # ignore for this script enc = conn.recvline().rstrip()[:-1] res_byte_string = pycryptonight.cn_slow_hash(binascii.unhexlify(enc), variant=1) sol = binascii.hexlify(res_byte_string) sol += b'\n' print(">> sending %s" % sol) conn.send(sol) print(">> received:\n%s" % conn.recvline()) conn.close()
def test_slow1(self): self.tst_method('tests-slow-1.txt', lambda x: pycryptonight.cn_slow_hash(x, 1))
def hash(self): return pycryptonight.cn_slow_hash(self.header, 4)
def test_slow4(self): self.tst_method('tests-slow-4.txt', lambda x, y: pycryptonight.cn_slow_hash(x, 4, 0, y))
#!/usr/bin/python import pycryptonight import sys import os import flag original = "0100fb8e8ac805899323371bb790db19218afd8db8e3755d8b90f39b3d5506a9abce4fa912244500000000ee8146d49fa93ee724deb57d12cbc6c6f3b924d946127c7a97418f9348828f0f02" hashed = "87c4e570653eb4c2b42b7a0d546559452dfab573b82ec52f152b7ff98e79446f" assert(pycryptonight.cn_slow_hash(original.decode("hex"), 1) == hashed.decode("hex")) def write(data, endl='\n'): sys.stdout.write(data + endl) sys.stdout.flush() def main(): write("%s -> %s" % (original, hashed)) randomed = os.urandom(2000) result = pycryptonight.cn_slow_hash(randomed, 1).encode("hex") write(randomed.encode("hex") + "?") answer = sys.stdin.readline().strip() if answer == result: write("Flag: %s" % flag.flag) else: write("No.") if __name__ == "__main__": main()