Exemplo n.º 1
0
Arquivo: node.py Projeto: youht88/bc
 def peerHttp(self, path, timeout=3, cb=None, percent=1, nodes=[], *cbArgs):
     if nodes == []:
         nodes = self.getRandom(percent)
     threads = []
     event = Event()
     for i, peer in enumerate(nodes):
         slash = '/' if path[0] != '/' else ''
         if type(path) == str:
             url = "http://" + peer + slash + path
         elif type(path) == list:
             length = len(path)
             url = "http://" + peer + slash + path[i % length]
         else:
             url = "http://" + peer
         threads.append(
             utils.CommonThread(self.httpProcess,
                                (url, timeout, cb, cbArgs)))
         Node.logger.info(url)
     for j in threads:
         j.setDaemon(True)
         j.start()
     for j in threads:
         j.join()
     result = []
     for k in threads:
         result.append(k.getResult())
     return result
Exemplo n.º 2
0
Arquivo: node.py Projeto: youht88/bc
 def setSocketio(self, socketio):
     self.socketio = socketio
     ClientNS.node = self
     if self.entryNode != self.me:
         self.socketioClient = SocketioClient(self.entryNode, ClientNS, '',
                                              self.me)
     else:
         self.socketioClient = None
     connected = self.connectEntryNode(self.entryNode)
     print("[connected]", connected)
     self.checkNodes = utils.CommonThread(self.checkConnectedNode, ())
     self.checkNodes.setDaemon(True)
     self.checkNodes.start()
     if not connected:
         Node.logger.critical("wait for confirm connected.")
         self.connected.wait()
Exemplo n.º 3
0
 def connect(self):
     self.thread = utils.CommonThread(self._connect, ())
     self.thread.setDaemon(True)
     self.thread.start()
     self.connecting.wait(5)
Exemplo n.º 4
0
Arquivo: miner.py Projeto: youht88/bc
def syn2(key,value,node):
  utils.CommonThread(myGossip.syn2,(key,value,node)).start()
  return "syn2 ok"
Exemplo n.º 5
0
Arquivo: miner.py Projeto: youht88/bc
def ack(key,node):
  utils.CommonThread(myGossip.ack,(key,node)).start()
  return "ack ok"
Exemplo n.º 6
0
Arquivo: miner.py Projeto: youht88/bc
def syn1(key,valHash,node):
  utils.CommonThread(myGossip.syn1,(key,valHash,node)).start()
  #myGossip.syn1(key,valHash,node)
  return "syn1 ok"
Exemplo n.º 7
0
Arquivo: miner.py Projeto: youht88/bc
def cli(key,value):
  t1=utils.CommonThread(myGossip.cli,(key,value))
  t1.start()
  t1.join()
  #myGossip.cli(key,value)
  return t1.getResult()
Exemplo n.º 8
0
Arquivo: miner.py Projeto: youht88/bc
      except:
        minindex = maxindex + 1
      if maxindex + 1 <= minindex - 1:  
        if node.socketioClient and node.socketioClient.client:
          node.emit("getBlocks",(maxindex + 1,minindex - 1))
        node.eBlockSyncing.set()
        continue
      if len(sets) >=1 and sets != prevSets:
        prevSets = sets
        node.blockPoolSync()
    except Exception as e:
      log.critical(traceback.format_exc())
    node.eBlockSyncing.set() #放行blocksync
    #time.sleep(2)
    
blocker=utils.CommonThread(blockerProcess,())
blocker.setDaemon(True)
blocker.start()

log.info("miner is ready")

#sync utxo
node.resetUTXO()

def minerProcess():
  while True:
    if args.debug and len(threading.enumerate())!=4: #debug调试时使用
      continue
    node.eMining.wait()
    node.eBlockSyncing.wait()
    node.eMining.clear()
Exemplo n.º 9
0
Arquivo: node.py Projeto: youht88/bc
    def resolveFork(self, forkBlock):
        blocks = [forkBlock]
        index = forkBlock.index - 1
        Node.logger.info("fork0.begin resolveFork,fork is {}-{}".format(
            blocks[0].index, blocks[0].nonce))
        while True:
            fork = blocks[-1]
            fileset = [
                item for item in self.database["blockpool"].find(
                    {"index": index}, {"_id": 0})
            ]
            i = -1
            if len(fileset) == 0:
                Node.logger.info(
                    "not find prev block #{} in blockPool".format(index))
                url = "http://{}/blockchain/get/{}/{}".format(
                    self.me, self.entryNode, index)
                Node.logger.critical("resolveForm", url)
                utils.CommonThread(self.httpProcess, (url))
                break
            recursion = False
            for i, blockDict in enumerate(fileset):
                block = Block(blockDict)
                Node.logger.info("fork1.poolblock {}-{} isValid?".format(
                    block.index, block.nonce))
                if block.isValid():
                    Node.logger.info(
                        "fork2.forkblock({}-{}) can link poolblock({}-{})?".
                        format(fork.index, fork.nonce, block.index,
                               block.nonce))
                    if fork.prev_hash != block.hash:
                        continue
                    if index > 0:
                        Node.logger.critical(index, block.index, '-',
                                             block.nonce)
                        Node.logger.info(
                            "fork3.poolblock({}-{}) can link blockchain({}-{})?"
                            .format(
                                block.index, block.nonce,
                                self.blockchain.findBlockByIndex(index -
                                                                 1).index,
                                self.blockchain.findBlockByIndex(index -
                                                                 1).nonce))
                    else:
                        Node.logger.info(
                            "fork3.poolblock({}-{}) isGenesisblock?".format(
                                block.index, block.nonce, index))
                    blocks.append(block)
                    if index == 0 or block.prev_hash == self.blockchain.findBlockByIndex(
                            index - 1).hash:
                        #done,replace blocks in blockchain,move correspondent into blockPool
                        Node.logger.info(
                            "forkstep1> move correspondent into blockPool")
                        index = block.index - 1

                        for b in blocks[1:]:
                            idx = b.index
                            Node.logger.debug(
                                "fork6.moveBlockToPool {}-{}".format(
                                    idx, self.blockchain.blocks[idx].nonce))
                            self.blockchain.moveBlockToPool(idx)

                        Node.logger.info("forkstep2> add new blocks")
                        blocks.reverse()
                        for b in blocks:
                            Node.logger.info("fork8.addblock {}-{}".format(
                                b.index, b.nonce))
                            if self.blockchain.addBlock(b):
                                Node.logger.info("fork9.UTXO")
                                if b.index == 0:
                                    doutxo = self.resetUTXO()
                                else:
                                    doutxo = self.updateUTXO(b)
                                if doutxo:
                                    Node.logger.info("fork10.txPoolRemove")
                                    self.txPoolRemove(b)
                                    Node.logger.info("fork11.save")
                                    b.save()
                                    Node.logger.info("fork12.removeFromPool")
                                    b.removeFromPool()
                                    Node.logger.info("fork13.next")
                                else:
                                    Node.logger.info("utxo error!")
                                    self.blockchain.blocks.pop()
                                    return True
                        return True
                    else:
                        index = block.index - 1
                        Node.logger.info("fork4.nextblock {}".format(index))
                        recursion = True
                        break
            if i == len(fileset) - 1 and not recursion:
                Node.logger.info(
                    "fork14.find prev block in blockPool,but none can link fork block or can link main chain"
                )
                if index == 0:
                    url = "http://{}/blockchain/get/{}/{}".format(
                        self.me, self.entryNode, 0)
                else:
                    url = "http://{}/blockchain/get/{}/{}".format(
                        self.me, self.entryNode, index - 1)
                Node.logger.critical("resolveForm", url)
                #utils.CommonThread(self.httpProcess,(url))
                break
        return False