def test_get_memory_poll_tx_state(self): tx_hash = '0000000000000000000000000000000000000000000000000000000000000000' try: restful_client.get_memory_pool_tx_state(tx_hash) except SDKException as e: self.assertIn('UNKNOWN TRANSACTION', e.args[1]) contract_address = '1ddbb682743e9d9e2b71ff419e97a9358c5c4ee9' sdk = OntologySdk() rpc_address = choice(TEST_RPC_ADDRESS) sdk.rpc.set_address(rpc_address) oep4 = sdk.neo_vm.oep4() oep4.hex_contract_address = contract_address from_acct = acct4 gas_limit = 20000000 gas_price = 500 b58_to_address = acct3.get_address_base58() value = 10 tx_hash = oep4.transfer(from_acct, b58_to_address, value, from_acct, gas_limit, gas_price) self.assertEqual(64, len(tx_hash)) try: tx_state = restful_client.get_memory_pool_tx_state(tx_hash) self.assertGreaterEqual(tx_state[0]['Height'], 0) self.assertGreaterEqual(tx_state[1]['Height'], 0) except SDKException: pass
def test_set_default_identity_by_ont_id(self): wm = WalletManager() self.assertRaises(SDKException, wm.open_wallet) wm.create_wallet_file(path) try: wm.open_wallet(path) size = 3 for i in range(size): private_key = utils.get_random_hex_str(64) wm.create_identity_from_private_key("ide", str(i), private_key) identities = wm.get_wallet().get_identities() self.assertEqual(len(identities), size) self.assertRaises(SDKException, wm.get_wallet().set_default_identity_by_ont_id, '') ont_id_list = list() for identity in wm.get_wallet().identities: ont_id_list.append(identity.ont_id) for _ in range(size * 5): rand_ont_id = choice(ont_id_list) wm.get_wallet().set_default_identity_by_ont_id(rand_ont_id) default_identity = wm.get_default_identity() self.assertEqual(rand_ont_id, default_identity.ont_id) finally: wm.del_wallet_file()
def test_get_account_by_index(self): test_id = "test_ont_id" size = 10 wallet, address_list = self.create_wallet_data(test_id, size) for _ in range(size * 2): index = choice(range(size)) acct = wallet.get_account_by_index(index) self.assertEqual(address_list[index], acct.b58_address)
def test_get_account_by_address(self): test_id = "test_ont_id" size = 10 wallet, address_list = self.create_wallet_data(test_id, size) for _ in range(size * 2): rand_address = choice(address_list) acct = wallet.get_account_by_b58_address(rand_address) self.assertEqual(rand_address, acct.b58_address)
def genkey(length=64): """ Generer nøgle """ return ''.join(random.choice(string.punctuation + string.ascii_letters + string.digits) for _ in range(length))
def __init__(self, outbox=None): Thread.__init__(self) self.inbox = SimpleQueue() self.outbox = outbox self.N = _N self.g = _G self.Ka, self.KA = dhlib.gen_key(self.N, self.g) # client DH key self.mel, self.pwd = random.choice(IDS) print(f'Client: {self.mel.decode()}:{self.pwd.decode()}')
def test_remove_account(self): test_id = "test_ont_id" size = 10 wallet, address_list = self.create_wallet_data(test_id, size) for i in range(size): rand_address = choice(address_list) wallet.remove_account(rand_address) address_list.remove(rand_address) self.assertEqual(len(wallet.accounts), size - i - 1)
def get_db_prep_value(self, value, connection=None, prepared=False): if value is None: return None if PYTHON3 is True: value = bytes(value.encode('utf-8')) else: value = smart_str(value) if not self._is_encrypted(value): padding = self._get_padding(value) if padding > 0: if PYTHON3 is True: value += bytes("\0".encode('utf-8')) + bytes( ''.encode('utf-8')).join([ bytes( random.choice( string.printable).encode('utf-8')) for index in range(padding - 1) ]) else: value += "\0" + ''.join([ random.choice(string.printable) for index in range(padding - 1) ]) if self.block_type != DEFAULT_BLOCK_TYPE: self.cipher = self.cipher_object.new( self.secret_key, getattr(self.cipher_object, self.block_type), self.iv) if PYTHON3 is True: value = self.prefix + binascii.b2a_hex( self.iv + self.cipher.encrypt(value)).decode('utf-8') else: value = self.prefix + binascii.b2a_hex( self.iv + self.cipher.encrypt(value)) else: if PYTHON3 is True: value = self.prefix + binascii.b2a_hex( self.cipher.encrypt(value)).decode('utf-8') else: value = self.prefix + binascii.b2a_hex( self.cipher.encrypt(value)) return value
def encrypt(inp: bytes): key = get_random_bytes(16) s = get_random_bytes(random.randint(4, 11)) e = get_random_bytes(random.randint(4, 11)) inp = s + inp + e inp = padpkcs7(inp, 16) iv = get_random_bytes(16) isCBC = random.choice([True, False]) if isCBC: out = CBCE(inp, iv, key).hex() else: aes = AES.new(key, AES.MODE_ECB) out = aes.encrypt(inp).hex() return out, isCBC
def test_get_account_by_address(self): test_id = "test_ont_id" wallet = WalletData(default_id=test_id) size = 10 address_list = list() for i in range(size): address = randint(0, 1000000000) acct = AccountData(b58_address=address) wallet.add_account(acct) address_list.append(address) self.assertEqual(len(wallet.accounts), i + 1) for i in range(size * 2): rand_address = choice(address_list) acct = wallet.get_account_by_b58_address(rand_address) self.assertEqual(rand_address, acct.b58_address)
def test_remove_account(self): test_id = "test_ont_id" wallet = WalletData(default_id=test_id) size = 10 address_list = list() for i in range(size): address = randint(0, 1000000000) acct = AccountData(b58_address=address) wallet.add_account(acct) address_list.append(address) self.assertEqual(len(wallet.accounts), i + 1) for i in range(size): rand_address = choice(address_list) wallet.remove_account(rand_address) address_list.remove(rand_address) self.assertEqual(len(wallet.accounts), size - i - 1)
def test_remove_identity(self): test_id = "test_ont_id" wallet = WalletData(default_id=test_id) size = 10 id_list = list() for i in range(size): try: rand_id = str(randint(0, 1000000000)) Identity(ont_id=rand_id) except SDKException as e: self.assertTrue(isinstance(e, SDKException)) rand_id = DID_ONT + str(randint(0, 1000000000)) identity = Identity(ont_id=rand_id) wallet.add_identity(identity) id_list.append(rand_id) self.assertEqual(len(wallet.get_identities()), i + 1) for i in range(size): rand_id = choice(id_list) wallet.remove_identity(rand_id) id_list.remove(rand_id) self.assertEqual(len(wallet.get_identities()), size - i - 1)
def genrandomid(words_in_random_id=DEFAULT_WORDS_IN_RANDOM_ID, locale='en'): return ' '.join(random.choice(_get_wordlist(locale)) for x in range(words_in_random_id))
def connect_to_main_net(self): restful_address = choice(MAIN_RESTFUL_ADDRESS) self.set_address(restful_address)
def connect_to_test_net(self): restful_address = choice(TEST_RESTFUL_ADDRESS) self.set_address(restful_address)
def display_id(): return ' '.join([random.choice(adjectives), random.choice(nouns)])
import unittest from Cryptodome.Random.random import choice from test import acct4, acct3 from ontology.ont_sdk import OntologySdk from ontology.common.address import Address from ontology.account.account import Account from ontology.network.rpc import TEST_RPC_ADDRESS from ontology.exception.exception import SDKException from ontology.network.restful import TEST_RESTFUL_ADDRESS from ontology.crypto.signature_scheme import SignatureScheme from ontology.utils.contract_data_parser import ContractDataParser restful_address = choice(TEST_RESTFUL_ADDRESS) sdk = OntologySdk(restful_address=restful_address) restful_client = sdk.restful class TestRestfulClient(unittest.TestCase): def test_get_version(self): version = restful_client.get_version() self.assertIn('v', version) def test_get_connection_count(self): count = restful_client.get_connection_count() self.assertGreaterEqual(count, 0) def test_get_block_height(self): height = restful_client.get_block_height()
def get_random_main_restful_address(): return choice(MAIN_RESTFUL_ADDRESS)
def get_random_main_rpc_address(): return choice(MAIN_RPC_ADDRESS)
def get_random_test_rpc_address(): return choice(TEST_RPC_ADDRESS)
def connect_to_main_net(self): rpc_address = choice(MAIN_RPC_ADDRESS) self.set_address(rpc_address)
def intercept(): msg = base64.b64decode(random.choice(_DATA)) iv = get_random_bytes(BS) ciph = AES.new(_KEY, AES.MODE_CBC, iv=iv).encrypt(pad(msg, BS)) return (iv, ciph)
def genrandomid(words_in_random_id=DEFAULT_WORDS_IN_RANDOM_ID, locale='en'): return ' '.join( random.choice(_get_wordlist(locale)) for x in range(words_in_random_id))
def randomString(n): thestring = '' charset = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPOQRSTUVWXYZ' for i in range(n): thestring += choice(charset) return thestring
def get_random_test_restful_address(): choice(TEST_RESTFUL_ADDRESS)
def runTest(self): """Cryptodome.Random.new()""" # Import the Random module and try to use it from Cryptodome import Random randobj = Random.new() x = randobj.read(16) y = randobj.read(16) self.assertNotEqual(x, y) z = Random.get_random_bytes(16) self.assertNotEqual(x, z) self.assertNotEqual(y, z) # Test the Random.random module, which # implements a subset of Python's random API # Not implemented: # seed(), getstate(), setstate(), jumpahead() # random(), uniform(), triangular(), betavariate() # expovariate(), gammavariate(), gauss(), # longnormvariate(), normalvariate(), # vonmisesvariate(), paretovariate() # weibullvariate() # WichmannHill(), whseed(), SystemRandom() from Cryptodome.Random import random x = random.getrandbits(16 * 8) y = random.getrandbits(16 * 8) self.assertNotEqual(x, y) # Test randrange if x > y: start = y stop = x else: start = x stop = y for step in range(1, 10): x = random.randrange(start, stop, step) y = random.randrange(start, stop, step) self.assertNotEqual(x, y) self.assertEqual(start <= x < stop, True) self.assertEqual(start <= y < stop, True) self.assertEqual((x - start) % step, 0) self.assertEqual((y - start) % step, 0) for i in range(10): self.assertEqual(random.randrange(1, 2), 1) self.assertRaises(ValueError, random.randrange, start, start) self.assertRaises(ValueError, random.randrange, stop, start, step) self.assertRaises(TypeError, random.randrange, start, stop, step, step) self.assertRaises(TypeError, random.randrange, start, stop, "1") self.assertRaises(TypeError, random.randrange, "1", stop, step) self.assertRaises(TypeError, random.randrange, 1, "2", step) self.assertRaises(ValueError, random.randrange, start, stop, 0) # Test randint x = random.randint(start, stop) y = random.randint(start, stop) self.assertNotEqual(x, y) self.assertEqual(start <= x <= stop, True) self.assertEqual(start <= y <= stop, True) for i in range(10): self.assertEqual(random.randint(1, 1), 1) self.assertRaises(ValueError, random.randint, stop, start) self.assertRaises(TypeError, random.randint, start, stop, step) self.assertRaises(TypeError, random.randint, "1", stop) self.assertRaises(TypeError, random.randint, 1, "2") # Test choice seq = range(10000) x = random.choice(seq) y = random.choice(seq) self.assertNotEqual(x, y) self.assertEqual(x in seq, True) self.assertEqual(y in seq, True) for i in range(10): self.assertEqual(random.choice((1, 2, 3)) in (1, 2, 3), True) self.assertEqual(random.choice([1, 2, 3]) in [1, 2, 3], True) if sys.version_info[0] is 3: self.assertEqual( random.choice(bytearray(b('123'))) in bytearray(b('123')), True) self.assertEqual(1, random.choice([1])) self.assertRaises(IndexError, random.choice, []) self.assertRaises(TypeError, random.choice, 1) # Test shuffle. Lacks random parameter to specify function. # Make copies of seq seq = range(500) x = list(seq) y = list(seq) random.shuffle(x) random.shuffle(y) self.assertNotEqual(x, y) self.assertEqual(len(seq), len(x)) self.assertEqual(len(seq), len(y)) for i in range(len(seq)): self.assertEqual(x[i] in seq, True) self.assertEqual(y[i] in seq, True) self.assertEqual(seq[i] in x, True) self.assertEqual(seq[i] in y, True) z = [1] random.shuffle(z) self.assertEqual(z, [1]) if sys.version_info[0] == 3: z = bytearray(b('12')) random.shuffle(z) self.assertEqual(b('1') in z, True) self.assertRaises(TypeError, random.shuffle, b('12')) self.assertRaises(TypeError, random.shuffle, 1) self.assertRaises(TypeError, random.shuffle, "11") self.assertRaises(TypeError, random.shuffle, (1, 2)) # 2to3 wraps a list() around it, alas - but I want to shoot # myself in the foot here! :D # if sys.version_info[0] == 3: # self.assertRaises(TypeError, random.shuffle, range(3)) # Test sample x = random.sample(seq, 20) y = random.sample(seq, 20) self.assertNotEqual(x, y) for i in range(20): self.assertEqual(x[i] in seq, True) self.assertEqual(y[i] in seq, True) z = random.sample([1], 1) self.assertEqual(z, [1]) z = random.sample((1, 2, 3), 1) self.assertEqual(z[0] in (1, 2, 3), True) z = random.sample("123", 1) self.assertEqual(z[0] in "123", True) z = random.sample(range(3), 1) self.assertEqual(z[0] in range(3), True) if sys.version_info[0] == 3: z = random.sample(b("123"), 1) self.assertEqual(z[0] in b("123"), True) z = random.sample(bytearray(b("123")), 1) self.assertEqual(z[0] in bytearray(b("123")), True) self.assertRaises(TypeError, random.sample, 1)
def runTest(self): """Cryptodome.Random.new()""" # Import the Random module and try to use it from Cryptodome import Random randobj = Random.new() x = randobj.read(16) y = randobj.read(16) self.assertNotEqual(x, y) z = Random.get_random_bytes(16) self.assertNotEqual(x, z) self.assertNotEqual(y, z) # Test the Random.random module, which # implements a subset of Python's random API # Not implemented: # seed(), getstate(), setstate(), jumpahead() # random(), uniform(), triangular(), betavariate() # expovariate(), gammavariate(), gauss(), # longnormvariate(), normalvariate(), # vonmisesvariate(), paretovariate() # weibullvariate() # WichmannHill(), whseed(), SystemRandom() from Cryptodome.Random import random x = random.getrandbits(16*8) y = random.getrandbits(16*8) self.assertNotEqual(x, y) # Test randrange if x>y: start = y stop = x else: start = x stop = y for step in range(1,10): x = random.randrange(start,stop,step) y = random.randrange(start,stop,step) self.assertNotEqual(x, y) self.assertEqual(start <= x < stop, True) self.assertEqual(start <= y < stop, True) self.assertEqual((x - start) % step, 0) self.assertEqual((y - start) % step, 0) for i in range(10): self.assertEqual(random.randrange(1,2), 1) self.assertRaises(ValueError, random.randrange, start, start) self.assertRaises(ValueError, random.randrange, stop, start, step) self.assertRaises(TypeError, random.randrange, start, stop, step, step) self.assertRaises(TypeError, random.randrange, start, stop, "1") self.assertRaises(TypeError, random.randrange, "1", stop, step) self.assertRaises(TypeError, random.randrange, 1, "2", step) self.assertRaises(ValueError, random.randrange, start, stop, 0) # Test randint x = random.randint(start,stop) y = random.randint(start,stop) self.assertNotEqual(x, y) self.assertEqual(start <= x <= stop, True) self.assertEqual(start <= y <= stop, True) for i in range(10): self.assertEqual(random.randint(1,1), 1) self.assertRaises(ValueError, random.randint, stop, start) self.assertRaises(TypeError, random.randint, start, stop, step) self.assertRaises(TypeError, random.randint, "1", stop) self.assertRaises(TypeError, random.randint, 1, "2") # Test choice seq = range(10000) x = random.choice(seq) y = random.choice(seq) self.assertNotEqual(x, y) self.assertEqual(x in seq, True) self.assertEqual(y in seq, True) for i in range(10): self.assertEqual(random.choice((1,2,3)) in (1,2,3), True) self.assertEqual(random.choice([1,2,3]) in [1,2,3], True) if sys.version_info[0] is 3: self.assertEqual(random.choice(bytearray(b('123'))) in bytearray(b('123')), True) self.assertEqual(1, random.choice([1])) self.assertRaises(IndexError, random.choice, []) self.assertRaises(TypeError, random.choice, 1) # Test shuffle. Lacks random parameter to specify function. # Make copies of seq seq = range(500) x = list(seq) y = list(seq) random.shuffle(x) random.shuffle(y) self.assertNotEqual(x, y) self.assertEqual(len(seq), len(x)) self.assertEqual(len(seq), len(y)) for i in range(len(seq)): self.assertEqual(x[i] in seq, True) self.assertEqual(y[i] in seq, True) self.assertEqual(seq[i] in x, True) self.assertEqual(seq[i] in y, True) z = [1] random.shuffle(z) self.assertEqual(z, [1]) if sys.version_info[0] == 3: z = bytearray(b('12')) random.shuffle(z) self.assertEqual(b('1') in z, True) self.assertRaises(TypeError, random.shuffle, b('12')) self.assertRaises(TypeError, random.shuffle, 1) self.assertRaises(TypeError, random.shuffle, "11") self.assertRaises(TypeError, random.shuffle, (1,2)) # 2to3 wraps a list() around it, alas - but I want to shoot # myself in the foot here! :D # if sys.version_info[0] == 3: # self.assertRaises(TypeError, random.shuffle, range(3)) # Test sample x = random.sample(seq, 20) y = random.sample(seq, 20) self.assertNotEqual(x, y) for i in range(20): self.assertEqual(x[i] in seq, True) self.assertEqual(y[i] in seq, True) z = random.sample([1], 1) self.assertEqual(z, [1]) z = random.sample((1,2,3), 1) self.assertEqual(z[0] in (1,2,3), True) z = random.sample("123", 1) self.assertEqual(z[0] in "123", True) z = random.sample(range(3), 1) self.assertEqual(z[0] in range(3), True) if sys.version_info[0] == 3: z = random.sample(b("123"), 1) self.assertEqual(z[0] in b("123"), True) z = random.sample(bytearray(b("123")), 1) self.assertEqual(z[0] in bytearray(b("123")), True) self.assertRaises(TypeError, random.sample, 1)
def unreserved(size=64): return "".join([random.choice(BASECH) for _ in range(size)])
def Alice(bob, args): global NAME NAME = "Alice" primes = [i for i in sieve.primerange(1000, 5000)] prime = random.choice(primes) factor = factorint(prime - 1) fl = True X = None while fl: X = random.choice([i for i in range(3, prime - 2, 2)]) fl = False for i in factor.keys(): if not X % i: fl = True A = random.randint(2, prime - 2) C = pow(A, X, prime) print(log("Нужно доказать Бобу, что знаю X для решения уравнения")) print(log("{} ^ X = {} (mod {})".format(A, C, prime))) bob.send((A, C, prime)) print( log("Генерируем {} значений Ri < Prime-1 (столько нужно чтобы убедить Боба)" .format(args.n))) R = [random.randint(2, prime - 2) for i in range(args.n)] print( log("Вычисляем Hi = {} ^ Ri (mod {}) и посылаем Бобу".format(A, prime))) H = [pow(A, i, prime) for i in R] bob.send(H) print( log("Используя протокол бросания монетки генерируем {} битов".format( args.n))) # -- Бросание монетки с помощью корней -- qprime = prime while qprime == prime: qprime = random.choice(primes) pprime = qprime while pprime == prime or qprime == pprime: pprime = random.choice(primes) N = pprime * qprime print(log("Посылаем бобу {}(N) = {}(p) * {}(q)".format(N, pprime, qprime))) bob.send(N) Z = bob.recv() roots = [] rb = [] for i in Z: root = nthroot_mod(i, 2, N, True) root.sort() roots.append(root[:2]) rb.append(random.choice(roots[-1])) print(log("Пытаемся угадать вычеты и отправляем Бобу")) bob.send(rb) B = bob.recv() print(log("Получены биты B: {}".format(B))) r = bob.recv() print(log("Получены корни боба r")) Btemp = [] K = -1 for i in range(args.n): if (r[i] == rb[i]) and B[i]: if K < 0: K = i Btemp.append(1) elif (r[i] in roots[i]) and (not B[i]): Btemp.append(0) else: Btemp.append(-1) print(log("Биты по r Боба: {}".format(Btemp))) if -1 in Btemp: print(log("Что-то пошло не так !!!")) bob.send(-1) return else: bob.send(0) print( log("Генерируем сообщение M если Bi=0 то Ri, если Bi=1 то Ri-R{} mod (prime-1)" .format(K))) M = [(R[i] - R[K]) % (prime - 1) if B[i] else R[i] for i in range(args.n)] bob.send(M) print(log("Также посылаем Бобу X-R{} (mod prime-1)".format(K))) bob.send((X - R[K]) % (prime - 1))
filename = get_pow_eval_path() + '/' + get_filename(REPS, MIN, MAX, STEP) eval_dir = get_pow_eval_path() with open(filename, 'w') as fd: fd.write("------------------------HEADER------------------------\n") fd.write("PoW Eval") fd.write("Difficulty (from, to, step): {}\n".format( str((MIN, MAX, STEP)))) fd.write("Repetitions per config: {}\n".format(REPS)) fd.write("Difficulty; # Hash Operations; Repetition\n") fd.write("----------------------END-HEADER----------------------\n") for r in progressbar(range(0, REPS)): for diff in range(MIN, MAX, STEP): hash_operations = 0 # We use pre-generated but 'real' public keys, chosen randomly pubkey = choice(peers).public_key_hash() # We use a random merkleroothash merkle = sha256(getrandbits(256).to_bytes(32, 'big')).digest().hex() seed = _calc_powork_seed(pubkey, merkle) hash_operations += 1 # One hash operation for seed computation hash_operations += _calculate_hash_powork_nonce( diff, seed, NONCE_LENGTH, True) # Write Result with open(filename, 'a') as fd: fd.write('{};{:d};{}\n'.format(diff, hash_operations, r))
def connect_to_test_net(self): rpc_address = choice(TEST_RPC_ADDRESS) self.set_address(rpc_address)