def getBlockchain(my_peers): block_num = 0 peer = 'https://iitkbucks.pclub.in' r = requests.get(peer + '/getBlock/0') #print(r.content) #block0 = open('block0', 'rb').read() genesis_block = block() genesis_block.from_bytes(r.content) #genesis_block.from_bytes(block0) my_Blockchain = Blockchain(my_peers) my_Blockchain.block_reward = genesis_block.transactions[0].outputs[0].amount flag = my_Blockchain.addBlock(genesis_block) block_num += 1 flag = True while flag: #peer = random.choice(my_peers) r = requests.get(peer + '/getBlock/' + str(block_num)) if r.status_code == 200: nblock = block() nblock.from_bytes(r.content) flag = my_Blockchain.addBlock(nblock) if flag == 0: flag = True block_num += 1 else: flag = False return my_Blockchain
def main(): # Parse the command line arguments parser = argparse.ArgumentParser( description="Decide the Artificial Intelligence technique") parser.add_argument("gameMode", type=str) args = parser.parse_args() mode = args.gameMode print(args.gameMode) global dimension, rows, s, item dimension = 500 rows = 8 surface = pygame.display.set_mode((dimension, dimension)) s = snake((60, 0, 255), (3, 3)) item = block(randomItem(rows, s), color=(255, 0, 0)) flag = True clock = pygame.time.Clock() if args.gameMode == "breadth-first-search": s.shortest.constructGraph(s.body, item.pos) s.shortest.configure(s) elif args.gameMode == "hamilton": s.longest.constructGraph(s.body, item.pos) s.longest.configure(s) while flag: pygame.time.delay(50) clock.tick(10) s.move(args.gameMode) if s.body[0].pos == item.pos: s.addCube() item = block(randomItem(rows, s), color=(255, 0, 0)) if args.gameMode == "breadth-first-search": s.shortest.destroyGraph() s.shortest.constructGraph(s.body, item.pos) s.shortest.configure(s) elif args.gameMode == "hamilton": s.longest.destroyGraph() s.longest.constructGraph(s.body, item.pos) s.longest.configure(s) for x in range(len(s.body)): if s.body[x].pos in list(map(lambda z: z.pos, s.body[x + 1:])): print("Score: ", len(s.body)) message_box("You Lost!", "Play again") s.reset((4, 4)) if args.gameMode == "breadth-first-search": s.shortest.constructGraph(s.body, item.pos) s.shortest.configure(s) elif args.gameMode == "hamilton": s.longest.constructGraph(s.body, item.pos) s.longest.configure(s) break #break redrawWindow(surface, rows, dimension, s, item) pass
def move(self): pop = True if self.direction == Right: new_block = block(self.blocks[-1].x + 15, self.blocks[-1].y) if new_block.x >= screenWidth: return True elif self.direction == Left: new_block = block(self.blocks[-1].x - 15, self.blocks[-1].y) if new_block.x < 0: return True elif self.direction == Up: new_block = block(self.blocks[-1].x, self.blocks[-1].y - 15) if new_block.y < 0: return True elif self.direction == Down: new_block = block(self.blocks[-1].x, self.blocks[-1].y + 15) if new_block.y >= screenHeight: return True if new_block.x == foodBlock.x and new_block.y == foodBlock.y: global food food = False pop = False for i in self.blocks: if new_block.x == i.x and new_block.y == i.y: return True if pop: self.blocks.pop(0) self.blocks.append(new_block) return False
def add(self, blockchain, help, chainresult): print("To add more type ADD if you have added all files type END") s = input() if s == "END": if chainresult != []: print("Hash von " + str(chainresult) + " ist fehlerhaft.") self.blockchain = blockchain return if chainresult == []: block.block(str(help + 1), "Blockchain richtig.", "") self.blockchain = blockchain return if s == "ADD": print("Type the next block file path") file = input() help = help + 1 print(blockchain.chainlist) print(len(blockchain.chainlist)) blockfile = reader.reader(file) blockf = block.block(blockfile.fileblocknr, blockfile.filedata, blockchain, blockfile.nonce) if blockf.hash != blockfile.filehash: print(str(blockf.hash) + " File" + str(blockfile.filehash)) chainresult.append("Block " + str(help)) self.add(blockchain, help, chainresult)
def program(): proghead() block() if tk.token.code == CodeTable['.']: print("Success") else: raise SyntaxError("SyntaxError at line:{},column:{}".format( tk.token.line, tk.token.column))
def procdefi(): # 过程说明部分 if tk.token.code == CodeTable['PROCEDURE']: procedh.procedh() block.block() if tk.token.code == CodeTable[';']: tk.token=next(tk.tg) else: raise SyntaxError("SyntaxError at line:{},column:{}".format(tk.token.line, tk.token.column)) procsuff.procsuff()
def test_empty(): A = npr.randn(3, 0) B = npr.randn(3, 3) out = block([[A, B]]) assert np.linalg.norm(out - B) == 0.0 A = npr.randn(0, 3) B = npr.randn(3, 3) out = block([[A], [B]]) assert np.linalg.norm(out - B) == 0.0
def procsuff(): if tk.token.code != CodeTable['BEGIN']: procedh.procedh() block.block() if tk.token.code == CodeTable[';']: tk.token = next(tk.tg) else: raise SyntaxError("SyntaxError at line:{},column:{}".format( tk.token.line, tk.token.column)) procsuff()
def dice(): from block import block uselight() pushmatrix() translate(0.0, 1.0, -20.0) rotate(200, 'y') block(1, 0, 0, 0, 0, 0) translate(1.0, 0.0, 3.0) rotate(500, 'y') block(2, 0, 0, 0, 0, 0) popmatrix()
def __init__(self): self.x = screenWidth / 2 self.y = screenHeight / 2 self.length = 5 self.direction = Right block1 = block(screenWidth / 2 - 30, screenHeight / 2) block2 = block(screenWidth / 2 - 15, screenHeight / 2) block3 = block(screenWidth / 2, screenHeight / 2) block4 = block(screenWidth / 2 + 15, screenHeight / 2) block5 = block(screenWidth / 2 + 30, screenHeight / 2) self.blocks = [block1, block2, block3, block4, block5]
def __init__(self, in_channels=3, num_classes=10, blocks=None, multipl=None): super(REPVGG, self).__init__() self.blocks = blocks self.multipl = multipl self.in_channels = in_channels # self.main_REPVGG = self.main_architecture() self.g = nn.AdaptiveAvgPool2d(output_size=1) self.linear = nn.Linear(int(512 * multipl[3]), num_classes) layers = [] # stage0 multipl = self.multipl out_channels = min(64, int(64 * multipl[0])) in_channels = self.in_channels blocks = self.blocks layers += [ block(in_channels=in_channels, out_channels=out_channels, stride=(2, 2)) ] in_channels = min(64, int(64 * multipl[0])) # stage 1,2 ,3 4 for i in range(4): out_channels = int(64 * (2**i) * multipl[i]) layers += [ block(in_channels=in_channels, out_channels=out_channels, stride=(2, 2)) ] in_channels = out_channels for j in range(blocks[i] - 1): layers += [ block( in_channels=in_channels, out_channels=out_channels, stride=(1, 1), ) ] in_channels = out_channels self.layers = layers self.main_REPVGG = nn.Sequential(*layers)
def addCube(self): tail = self.body[-1] dx, dy = tail.directionX, tail.directionY if dx == 1 and dy == 0: self.body.append(block((tail.pos[0] - 1, tail.pos[1]))) elif dx == -1 and dy == 0: self.body.append(block((tail.pos[0] + 1, tail.pos[1]))) elif dx == 0 and dy == 1: self.body.append(block((tail.pos[0], tail.pos[1] - 1))) elif dx == 0 and dy == -1: self.body.append(block((tail.pos[0], tail.pos[1] + 1))) self.body[-1].directionX = dx self.body[-1].directionY = dy
def test_torch(): try: import torch except: print('Warning: PyTorch not found. Skipping tests.') return torch.manual_seed(0) nx, nineq, neq = 4, 6, 7 Q = torch.randn(nx, nx) G = torch.randn(nineq, nx) A = torch.randn(neq, nx) D = torch.diag(torch.rand(nineq)) K_ = torch.cat( (torch.cat((Q, torch.zeros(nx, nineq).type_as(Q), G.t(), A.t()), 1), torch.cat( (torch.zeros(nineq, nx).type_as(Q), D, torch.eye(nineq).type_as(Q), torch.zeros(nineq, neq).type_as(Q)), 1), torch.cat( (G, torch.eye(nineq).type_as(Q), torch.zeros( nineq, nineq + neq).type_as(Q)), 1), torch.cat((A, torch.zeros((neq, nineq + nineq + neq))), 1))) K = block( ((Q, 0, G.t(), A.t()), (0, D, 'I', 0), (G, 'I', 0, 0), (A, 0, 0, 0))) assert (K - K_).norm() == 0.0
def findBlock(index, previousHash, timestamp, data, difficulty): '''Creates a new valid block by finding the nonce value such that the created block satisfies current difficulty. Arguments: index: index of the block previousHash: hash the block preceding the new block timestamp: time when the new block is created data: data difficulty: current difficulty Returns: The new block generated with the correct nonce. ''' nonce = 0 while True: hash = calculateHash(index, previousHash, timestamp, data, difficulty, nonce) if hashMatchesDifficulty(hash, difficulty): return block(index, hash, previousHash, timestamp, data, difficulty, nonce) nonce += 1
def createBlock(self, txnList): pH = self.chain.chain[-1].hash if (txnList == []): return verifiedList = [] unverifiedList = [] # Verifying transactions {"Sender":S,"Message":msg,"Signature":signature} for T in txnList: idchecked = self.checkID(T['Sender']) encoded = str(T["Message"]).encode() hashedMsg = SHA.new(encoded) auth = PKCS1_v1_5.new(T['Sender'].pk) verified = auth.verify(hashedMsg, T['Signature']) if (idchecked and verified): verifiedList.append(T) else: unverifiedList.append(T) PoW = {'difficulty': 4} # Consider getting difficulty as parameter PoW['Hash'], PoW['nonce'] = self.__PoW(pH, verified) miner = self.address self.blocksmined += 1 self.rE -= (4 + random.random()) return block(pH, verifiedList, PoW, miner), unverifiedList
def test_linear_operator(): npr.seed(0) nx, nineq, neq = 4, 6, 7 Q = npr.randn(nx, nx) G = npr.randn(nineq, nx) A = npr.randn(neq, nx) D = np.diag(npr.rand(nineq)) K_ = np.bmat(((Q, np.zeros((nx, nineq)), G.T, A.T), (np.zeros( (nineq, nx)), D, np.eye(nineq), np.zeros( (nineq, neq))), (G, np.eye(nineq), np.zeros( (nineq, nineq + neq))), (A, np.zeros( (neq, nineq + nineq + neq))))) Q_lo = sla.aslinearoperator(Q) G_lo = sla.aslinearoperator(G) A_lo = sla.aslinearoperator(A) D_lo = sla.aslinearoperator(D) K = block(((Q_lo, 0, G_lo.H, A_lo.H), (0, D_lo, 'I', 0), (G_lo, 'I', 0, 0), (A_lo, 0, 0, 0))) w1 = np.random.randn(K_.shape[1]) assert np.allclose(K_.dot(w1), K.dot(w1)) w2 = np.random.randn(K_.shape[0]) assert np.allclose(K_.T.dot(w2), K.H.dot(w2)) W = np.random.randn(*K_.shape) assert np.allclose(K_.dot(W), K.dot(W))
def segment(img): # Read the image we saved #img = imread('testnew.jpg',0) # Segment into blocks # Threshold to pick the blocks from the background #ret,thresh = threshold(img,127,255,THRESH_BINARY) #show_image_window(thresh) patterns = import_patterns() # Now isolate the blocks img_gray = cvtColor(img, COLOR_BGR2GRAY) blocks = [] blockpts = [] for template, name in patterns: w, h = template.shape[::-1] res = matchTemplate(img_gray,template,TM_CCOEFF_NORMED) threshold = 0.7 loc = np.where(res >= threshold) print "searching for " + name for pt in zip(*loc[::-1]): # make sure the new point is new # Do some weedout here if not in_region(pt, blockpts, w, h): # Create a block object for each block newblock = blk.block(pt, (w,h), None, name) print "Found block: " + name blocks.append(newblock) blockpts.append(pt) # Write out a test image rectangle(img, pt, (pt[0]+w, pt[1]+h), (0,0,255), 2) imwrite('res.png',img) return blocks
def GenererBlocks(self): '''Genere les blocks de defense''' #_________________________________ for i in range(self.__nb_blocks): posX1 = (int(self.__canvas_len) / self.__nb_blocks) * i posX2 = (int(self.__canvas_len) / self.__nb_blocks) * (i + 1) self.__random = random.randint( 0, self.__coeff_block_inv ) #Genere un nombre aleatoire permettant de savoir si l'alien va tirer if self.__random == 1: invincible = True color = '#585e5d' else: invincible = False color = '#9b9b9b' block1 = block(posX1, self.__y1_bl, posX2, self.__y2_bl, invincible, color) corps_block = self.__canvas.create_rectangle( block1.Getx1(), block1.Gety1(), block1.Getx2(), block1.Gety2(), fill=block1.GetColor()) #Genere l'identite du block id_blc = self.GenererId(self.__blocks) #Ajoute le blocks aux dictionaires self.__blocks[id_blc] = block1 self.__corps_blocks[id_blc] = corps_block
def test_torch(): import torch torch.manual_seed(0) nx, nineq, neq = 4, 6, 7 Q = torch.randn(nx, nx) G = torch.randn(nineq, nx) A = torch.randn(neq, nx) D = torch.diag(torch.rand(nineq)) K_ = torch.cat( (torch.cat((Q, torch.zeros(nx, nineq).type_as(Q), G.t(), A.t()), 1), torch.cat( (torch.zeros(nineq, nx).type_as(Q), D, torch.eye(nineq).type_as(Q), torch.zeros(nineq, neq).type_as(Q)), 1), torch.cat( (G, torch.eye(nineq).type_as(Q), torch.zeros( nineq, nineq + neq).type_as(Q)), 1), torch.cat((A, torch.zeros((neq, nineq + nineq + neq))), 1))) K = block( ((Q, 0, G.t(), A.t()), (0, D, 'I', 0), (G, 'I', 0, 0), (A, 0, 0, 0))) assert (K - K_).norm() == 0.0
def load(self, file, template): """load from file. create an array that contains as many blocks as nessecary. """ self.file = file # large chunk of data data = file.read() # create parser used for pulling data from the header. header_parser = Lark(HEADER_GRAMAMAR) # find the header, and create an AST from the found header. header = re.search(r'@.(.*=.*)*', data) tree = header_parser.parse(header.group(0)) # use the data from the header to transform the terrain object # accordingly. HeaderTransformer(self).transform(tree) # make sure al data is OK. self.check_validity() # create new array for containing the blocks. y = 0 self.grid = numpy.empty(shape=(Y // self.size, X // self.size), dtype=block.Block) airsurf = pygame.Surface((10, 10)) airsurf.fill(self.air) watersurf = pygame.Surface((10, 10)) watersurf.fill(self.water) # iterate through all lines. for line in data.split('\n'): x = 0 if line.startswith((';', '@')): # entire comment/header line. continue continue # remove a comment if there is one line = line.split(';')[0].strip() if not line: # blank line continue # iterate through each character in the line for item in line: self.raw += line + '\n' try: self.grid[y][x] = block.block(item, template, airsurf, watersurf, (x, y)) except AssertionError: # not implemented, replace a pit/sign with air for now. self.grid[y][x] = block.Air((x, y), airsurf) x += 1 y += 1
def getBlocks(fileName, step=1024): f = open(fileName, 'rb') txt_as_byte = f.read() #txt_as_byte = str.encode(txt) start = 0 id = 1 blocks = [] length = len(txt_as_byte) for i in range(0, length, step): if i + step > length: blocks.append(block(id, 0, i, length, txt_as_byte[i:], 0)) else: blocks.append(block(id, 0, i, i + step, txt_as_byte[i:i + step], 0)) id += 1 #print(blocks[-1]) return blocks
def load_block_with_uncorrected_artifacts(name, fo = None): pp_id = name2pp_id(name) exp_type = name2exp_type(name) bid = name2bid(name) s = session.Session(pp_id,exp_type,fo) vmrk = s.vmrk log = s.log return block.block(s.pp_id,s.exp_type,s.vmrk,s.log,bid,fo,corrected_artifacts = False)
def __init__(self, n_way, block_size, write): self.set_data = [] self.block_size = block_size self.write = write i = 0 while i < n_way: self.set_data.append([0, block.block()]) i = i + 1
def __init__( self, chaintype ): #chaintypes should actually be subclasses. Will change later. self.chain = [block.block(0, "first transaction", 755, "Transaction")] self.chaintype = chaintype self.length = 1 self.users = {"Chase Leffers": chase} self.balance = {chase: 1500}
def __init__(self,transaction): ''' genera una cadena de blocs que es una llista de blocs, el primer bloc es un bloc "genesis" generat amb la transaccio "transaction" ''' self.list_of_blocks = [] b = block() b.genesis(transaction) self.list_of_blocks.append(b)
def __init__(self, color, pos): self.color = color self.head = block(pos) self.body.append(self.head) self.directionX = 0 self.directionY = 1 self.human = human() self.shortest = shortest_path() self.longest = longest_path() self.hamilton = hamilton()
def create_sq_grid(border, grid_size, block_radius, block_margin): global blocks for row in range(grid_size): for col in range(grid_size): x = border + col * (block_margin + block_radius * 2) y = border + row * (block_margin + block_radius * 2) b = block.block(x, y, 4, block_radius, WHITE, screen, math.pi / 4) blocks.append(b)
def __init__(self): self.privatekey = SigningKey.generate() self.publickey = self.privatekey.get_verifying_key() self.blockhead = None self.maxnumtrans = 1000 self.database = [[0] * 2 for i in range(self.maxnumtrans)] self.top = 0 self.currentblock = block.block(None) self.blockhead = Treenode() self.genesis = Treenode() # height will be zero for genesis block self.leafhead = self.genesis # head of the list of leaves, points to an empty node initially
def reset(self, pos): self.head = block(pos) self.body = [] self.body.append(self.head) self.turns = {} self.directionX = 0 self.directionY = 1 self.human = human() self.shortest = shortest_path() self.longest = longest_path() self.hamilton = hamilton()
def addgen(self, chainresult): print("Type the path of the next block file in the right order") genesisIn = input() gen = reader.reader(genesisIn) testChain = blockchain.blockchain([]) gent = block.block(gen.fileblocknr, gen.filedata, testChain, gen.nonce) print("genesis block has been added to the testchain") if gent.hash != gen.filehash: chainresult.append("Block 0") help = 0 self.add(testChain, help, chainresult)
def create_oct_sq_grid(border, grid_size, oct_radius, sq_radius, block_margin): global blocks # create octagons for row in range(grid_size): for col in range(grid_size): x = border + col * (block_margin + oct_radius * 2) y = border + row * (block_margin + oct_radius * 2) b = block.block(x, y, 8, oct_radius, WHITE, screen, math.pi / 8) blocks.append(b) # create squares apothem = oct_radius * math.cos(math.pi / 8) for row in range(grid_size - 1): for col in range(grid_size - 1): x = border + apothem + block_margin + col * ((block_margin) + oct_radius * 2) y = border + apothem + block_margin + row * ((block_margin) + oct_radius * 2) b = block.block(x, y, 4, sq_radius, WHITE, screen) blocks.append(b)
def add_block(self, drivers, driver_private_keys, miner_public_key, miner_private_key): prev_hash = self.get_latest_block().get_block_hash() new_entry = entry(drivers) new_block = block(new_entry, len(self.chain), prev_hash, miner_public_key, driver_private_keys) new_block.mine_block(self.difficulty) new_block.generate_miner_signature(miner_private_key) self.chain.append(new_block)
def handle_read(self): data = self.recv(8192) if data: data = block(data) name = everyone[self.socket] if name is None: everyone[self.socket]=data.strip() return #print("read %d bytes" % len(data)) for sock,name in everyone.items(): sock.send(str(name)+': '+data) else: self.handle_close()
def checkpropose(): global flag for i in range(block.block('None').max_trans_num) : if createnode.i_am.currentblock.translist[i] == None: print False #flag= False break # else we need to propose the current block after solving proof of work proof_of_work.proofofwork(createnode.i_am.currentblock) #print "Proof of work has been solved!" # convert the current block to file block.blocktofile(createnode.i_am.currentblock,blocktopropose) #flag= True print True
def partition_range(q, range_data, dix, diy): #part_factor = int(math.floor(num_avail_res ** 0.5)) part_factor = int(math.floor(config.blocks_num ** 0.5)) ndx = part_factor while (ndx > 1 and config.blocks_num % ndx != 0 ): ndx = ndx - 1 ndy = config.blocks_num / ndx sdx = (range_data[dix][1] - range_data[dix][0]) / ndx sdy = (range_data[diy][1] - range_data[diy][0]) / ndy print ndx, ndy new_range = copy.deepcopy(range_data) for idx in range(0, ndx): new_range[dix][0] = range_data[dix][0]+idx * sdx new_range[dix][1] = new_range[dix][0] + sdx for idy in range(0, ndy): new_range[diy][0] = range_data[diy][0]+ idy * sdy new_range[diy][1] = new_range[diy][0] + sdy q.queue.append(block.block(new_range))
import node import block import transaction import treestruct i_am = node.node() #creating a node instance for the peer i_am.blockhead.propblock = block.block(9999) i_am.publickey = "1" #teacher's public keys are kept static teacher1publickey = "1" teacher2publickey = "2" teacher3publickey = "3" teacher4publickey = "4" teacher5publickey = "5" student1publickey = "876" student2publickey = "567" student3publickey = "563" student4publickey = "890" student5publickey = "173" t1 = transaction.transaction(0,1) t1.sign = "signadmin" t1.hash = "100" t1.outlist = [transaction.outputtrans() for i in range (t1.outcount)] t1.outlist[0].value = transaction.transaction(0,0).STAR t1.outlist[0].addr = teacher1publickey i_am.blockhead.propblock.add_trans_to_block(t1)
from proof_of_work import * import transaction from treestruct import * import block import node # adding the block to the blockchain kept by node1, assuming this test is run from the node1's machine node0 = node.node() node1 = node.node() node2 = node.node() node3 = node.node() node4 = node.node() block1 = block.block(9999) #genesis hash #transaction 1 in the block sent by node0 with address 1000 t1 = transaction.transaction(0,2) t1.sign = "sign1" t1.hash = 12341 # no input trans but has two outputs t1.outlist = [transaction.outputtrans() for i in range (t1.outcount)] t1.outlist[0].value = 1 t1.outlist[0].addr = node1.publickey t1.outlist[1].value = 19 t1.outlist[1].addr = node0.publickey # adding trans1 to the block block1.translist[0] = t1 #transaction 2 in the block sent by node0 with address 1000
def validatetrans(self, node): # check 1 : check whether the transaction is already present in the outstanding block of the node or in the blockchain # part 1 : checking in the blockchain blockptr = node.blockhead while blockptr.parent != None and blockptr.propblockhash != 9999: # ie, search till the genesis block for i in range(blockptr.propblock.max_trans_num): if blockptr.propblock.translist[i].hash == self.hash: print "" print "Transaction already in the blockchain" return False blockptr = blockptr.parent # end check 1 # part 2 : checking in the block currently filled by the node if node.currentblock != None: for i in range(block.block(None).max_trans_num): """ print "inside for loop" print "node.currentblock.translist[i].hash" print node.currentblock.translist[i].hash print "self.hash" print self.hash """ if node.currentblock.translist[i].hash == self.hash: print "" print "Transaction already received" return False # check 2 : checking whether the inlist is empty, ie whether it is a special transaction in whcih the faculty gives STAR bitcoins to a student flag = 0 if self.incount == 0: flag = 1 print "" print "Invalid transaction, possible attempt to create coin" return False # end check 2 inputsum = 0 transptr = None blockhash = None for l in range(self.incount): # after each pass, one input transaction from the input list is verified transhash = self.inlist[l].hash for j in range(node.top): # iterate through all transactions in the database ie till 'top' transactions if node.database[j][0] == transhash: # if the transaction hash matches, then the block in which blockhash = node.database[j][1] break if blockhash == None: print "" print "Invalid input transaction, or has not yet made it to the blockchain" return False # finding the block in the blockchain using the blockhash blockptr = node.blockhead while blockptr.parent != None and blockptr.propblockhash != blockhash: # ie, search till the genesis block blockptr = blockptr.parent # searching for the transaction in the block using transaction hash for i in range(block.block(None).max_trans_num): if blockptr.propblock != None and blockptr.propblock.translist[i].hash == transhash: transptr = blockptr.propblock.translist[i] # transptr points to the input transaction break # check 3 : checking whether the inputs are already spent or not # checking whether the current transaction's (pointed by transptr) hash is given as the hash of any input to any transaction that comes after that ptr = node.blockhead while ptr != blockptr: for j in range(blockptr.propblock.max_trans_num): # every transaction in the block for k in range(ptr.propblock.incount): # every input to the transaction if ptr.propblock.inlist[k].hash == transptr.hash: # if input was spent, return false print "" print "Input already spent, possible double spent attempt!" return False """ for j in range(i+1, block.max_trans_num): # for those transactions that come after the input transaction for k in range(ptr.propblock.translist[j].incount): # every input to the transaction if ptr.propblock.translist[j].inlist[k].hash == transptr.hash: # if input was spent, return false print "problem is here and j is %d", j return False """ # end check 3 """ #verifying the signature(Not sure if it will work!) transstr = self.incount + self.outcount for i in range (self.incount): inliststr = str(self.inlist[i].hash) + str(self.inlist[i].n) + str(self.inlist[i].pub) assert node.publickey.verify(self.inlist[i].sign, inliststr) transstr = transstr + str(self.inlist[i].hash) + str(self.inlist[i].n) + str(self.inlist[i].pub) + str(self.inlist[i].sign) for i in range (self.outcount) : transstr = transstr + str(self.outlist[i].value) + str(self.outlist[i].addr) transstr = transstr + self.hash assert node.publickey.verify(self.sign, transstr) """ if transptr == None: print ("transptr is null") if flag != 1 and transptr != None: # ie checking whether its a transcation with empty inlist index = self.inlist[l].n address = self.inlist[l].pub inputsum = inputsum + transptr.outlist[index].value if transptr.outlist[index].addr != address: return False outputsum = 0 for i in range(self.outcount): outputsum = outputsum + self.outlist[i].value if flag == 1: # input list is empty if self.outcount != 1: print "" print "Invalid transaction, attempt for possible double spent!" return False if self.outcount == 1 and outputsum != self.STAR: print "" print "Invalid transaction, attempt for possible double spent!" return False else: if inputsum < outputsum: print "" print "Balance is less than the requested sum" return False print "" print "Transaction has been successfully verified" return True
def createblock(): node0 = node.node() node1 = node.node() node2 = node.node() node3 = node.node() node4 = node.node() block1 = block.block(9999) #genesis hash #transaction 1 in the block sent by node0 with address 1000 t1 = transaction.transaction(0,2) t1.sign = "sign1" t1.hash = 12341 # no input trans but has two outputs t1.outlist = [transaction.outputtrans() for i in range (t1.outcount)] t1.outlist[0].value = 1 t1.outlist[0].addr = node1.publickey t1.outlist[1].value = 19 t1.outlist[1].addr = node0.publickey # adding trans1 to the block block1.translist[0] = t1 #transaction 2 in the block sent by node0 with address 1000 t1 = transaction.transaction(1,2) t1.sign = "sign2" t1.hash = 12342 # input trans t1.inlist = [transaction.inputtrans() for i in range (t1.incount)] t1.inlist[0].hash = 12341 t1.inlist[0].n = 1 t1.inlist[0].sign = "signofnode0" t1.inlist[0].pub = node0.publickey # public key of node 0 # output trans t1.outlist = [transaction.outputtrans() for i in range (t1.outcount)] t1.outlist[0].value = 2 t1.outlist[0].addr = node2.publickey t1.outlist[1].value = 17 t1.outlist[1].addr = node0.publickey # adding trans1 to the block block1.translist[1] = t1 #transaction 3 in the block sent by node0 with address 1000 t1 = transaction.transaction(1,2) t1.sign = "sign3" t1.hash = 12343 # input trans t1.inlist = [transaction.inputtrans() for i in range (t1.incount)] t1.inlist[0].hash = 12342 t1.inlist[0].n = 1 t1.inlist[0].sign = "signofnode0" t1.inlist[0].pub = node0.publickey # public key of node 0 # output trans t1.outlist = [transaction.outputtrans() for i in range (t1.outcount)] t1.outlist[0].value = 5 t1.outlist[0].addr = node3.publickey t1.outlist[1].value = 12 t1.outlist[1].addr = node0.publickey # adding trans1 to the block block1.translist[2] = t1 #transaction 4 in the block sent by node0 with address 1000 t1 = transaction.transaction(1,2) t1.sign = "sign3" t1.hash = 12344 # input trans t1.inlist = [transaction.inputtrans() for i in range (t1.incount)] t1.inlist[0].hash = 12343 t1.inlist[0].n = 1 t1.inlist[0].sign = "signofnode0" t1.inlist[0].pub = node0.publickey # public key of node 0 # output trans t1.outlist = [transaction.outputtrans() for i in range (t1.outcount)] t1.outlist[0].value = 3 t1.outlist[0].addr = node4.publickey t1.outlist[1].value = 9 t1.outlist[1].addr = node0.publickey # adding trans1 to the block block1.translist[3] = t1 #transaction 5 in the block sent by node0 with address 1001 t1 = transaction.transaction(0,2) t1.sign = "sign5" t1.hash = 12345 # no input trans # output trans t1.outlist = [transaction.outputtrans() for i in range (t1.outcount)] t1.outlist[0].value = 5 t1.outlist[0].addr = 1002 t1.outlist[1].value = 15 t1.outlist[1].addr = 1001 # adding trans1 to the block block1.translist[4] = t1 return block1
import sqlite3 from block import block from script import script, scriptSig from blockutil import pkhash2addr from blockutil import pubkey2addr blockfile = '/home/marzig76/.bitcoin/blocks/blk00007.dat' blockstream = open(blockfile, 'rb') b = block(blockstream) # create db connection conn = sqlite3.connect('../blexplor-web/db.sqlite3') c = conn.cursor() # insert block insert_block = ( "INSERT INTO block_block " + "(magic_number, block_size, version, prev_hash, merkel_root, " + "block_time, target, nonce, tx_count, block_height)" + "VALUES " + "(?,?,?,?,?,?,?,?,?,0)" ) c.execute(insert_block, (b.magic_number, b.block_size, b.version, b.prev_hash, b.merkel_root, b.time, b.target, b.nonce, b.txcount)) conn.commit() # get last block id result = conn.execute("SELECT max(id) FROM block_block") for row in result: block_id = row[0]
from block_swap_avx import block_swap_avx import os if __name__ == '__main__': blen = [1,2,4,8,16] dirnames = [os.path.join('code',i) for i in ['block', 'block_swap', 'block_avx', 'block_swap_avx']] for dn in dirnames: if not os.path.exists(dn): os.mkdir(dn) for i in blen: for j in blen: b = 'code/block/block{0}x{1}.hpp'.format(i, j) bs = 'code/block_swap/block{0}x{1}_swap.hpp'.format(i, j) with open(b, 'w') as out: out.write(str(block(searchList=[{'N':i, 'M':j}]))) with open(bs, 'w') as out: out.write(str(block_swap(searchList=[{'N':i, 'M':j}]))) if j%4 == 0: ba = 'code/block_avx/block{0}x{1}_avx.hpp'.format(i, j) bsa = 'code/block_swap_avx/block{0}x{1}_swap_avx.hpp'.format(i, j) with open(ba, 'w') as out: out.write(str(block_avx(searchList=[{'N':i, 'M':j}]))) with open(bsa, 'w') as out: out.write(str(block_swap_avx(searchList=[{'N':i, 'M':j}]))) hb = 'code/block.hpp' hbs = 'code/block_swap.hpp' hba = 'code/block_avx.hpp' hbsa = 'code/block_swap_avx.hpp'
def setUp(self): '''Create an instance of the block object.''' self.my_block = block()
from block import block from script import script blockfile = '/home/marzig76/.bitcoin/blocks/blk00000.dat' blockstream = open(blockfile, 'rb') parsed_block = block(blockstream) print parsed_block # script examples # orig 76a914fb96940932cc00274cf6ce423623e0cb0aa32ccf88ac # 0x4c OP_PUSHDATA1 76a94c14fb96940932cc00274cf6ce423623e0cb0aa32ccf88ac # 0x4d OP_PUSHDATA2 76a94d0100deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef88ac # 0x4d OP_PUSHDATA2 76a94d0001ff88ac # 0x4e OP_PUSHDATA4 76a94e00000001ff88ac # 0x6a OP_RETURN 6a13636861726c6579206c6f766573206865696469 pk_script = script('6a13636861726c6579206c6f766573206865696469'.decode('hex')) print pk_script
import block from treestruct import * import node node0 = node.node() node2 = node.node() node3 = node.node() node4 = node.node() genesis = Treenode() B = block.block(None) node0.currentblock = B #transaction 2 in the block sent by node0 with address 1000 t1 = transaction.transaction(1,2) t1.sign = "sign2" t1.hash = 12342 # input trans t1.inlist = [transaction.inputtrans() for i in range (t1.incount)] t1.inlist[0].hash = 12341 t1.inlist[0].n = 1 t1.inlist[0].sign = "signofnode0" t1.inlist[0].pub = node0.publickey # public key of node 0 # output trans t1.outlist = [transaction.outputtrans() for i in range (t1.outcount)] t1.outlist[0].value = 2 t1.outlist[0].addr = node2.publickey t1.outlist[1].value = 17 t1.outlist[1].addr = node0.publickey node0.currentblock=node0.currentblock.add_trans_to_block(t1)