首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用post API添加

如何使用post API添加
EN

Stack Overflow用户
提问于 2020-03-23 13:18:41
回答 1查看 40关注 0票数 0

,我想写这个关于区块链的项目,它有获取块的功能,也有添加新块的功能。我正在挣扎的是使用API在链中添加一个新块。现在,程序正在以这样的方式添加块:

const BChain =新bs.BlockChain();

BChain.addBlock({发件人:“Customer”,reciver:“供应者-4”,数量: 100});

BlockChain.js

代码语言:javascript
复制
class Block {
   constructor(index, data, prevHash, timestamp, hash) {


       this.index = index;
      if(timestamp === undefined)  this.timestamp = Math.floor(Date.now() / 1000); else this.timestamp = timestamp;
       this.data = data;
       this.prevHash = prevHash;
       if(hash === undefined)    this.hash=this.getHash();else this.hash = hash;
   }

   getHash() {
       let encript=JSON.stringify(this.data) + this.prevHash + this.index + this.timestamp;
       let hash=crypto.createHmac('sha256', "secret")
       .update(encript)
       .digest('hex');
       return hash;
   }
}


class BlockChain {
   constructor() {
    if(arguments.length>0)
    {
         Object.assign(this, arguments[0]);
         for (var i = 0; i <    this.chain.length; i++) {
            this.chain[i] = new Block(this.chain[i].index, this.chain[i].data, this.chain[i].prevHash, this.chain[i].timestamp,this.chain[i].hash);

        }
    }
    else{
        this.chain = [];
    }
   }


   addBlock(data) {
       let index = this.chain.length;
       let prevHash = this.chain.length !== 0 ? this.chain[this.chain.length - 1].hash : 0;
       let block = new Block(index, data, prevHash);
       this.chain.push(block);
   }


    getBlockByID(id){
        for(let i=0;i<this.chain.length;i++){
            if(this.chain[i].index == id)
            return this.chain[i];
        }

    }

    storeChain(path){
        let str = JSON.stringify(this);
        fs.writeFileSync(path,str);
    }
}

function loadChain(path) {
    let str = fs.readFileSync(path)
    let obj = JSON.parse(str);
    const BChain2 =new BlockChain(obj);
    return BChain2

}


module.exports ={
    Block: Block,
    BlockChain : BlockChain,
    loadChain: loadChain
};

Index.js

代码语言:javascript
复制
const port = 8000;

const app = express();



const BChain = new bs.BlockChain();
BChain.addBlock({sender: "Customer-A", reciver: "Supplier-4", amount: 100});
BChain.addBlock({sender: "OEM-7", reciver: "Customer-B", invoice: '908987897'});
BChain.addBlock({sender: "Test5", reciver: "Customer-A", amount: 75});



const chain_path = path.resolve(__dirname, '..','./data/chain.json');
const data_path = path.resolve(__dirname, '..','./data/');


if (!fs.existsSync(data_path)){
    fs.mkdirSync(data_path);
}


BChain.storeChain(chain_path);


BChain2 = bs.loadChain(chain_path);

app.get('/' ,(req,res)=>{
res.send('Hello World');
});

app.get('/api/getchain' ,(req,res)=>{
    res.send(JSON.stringify(BChain2.chain));
});


app.get('/api/getblock' ,(req,res)=>{
    let id = req.query.id;
    console.log(id);
    res.send(JSON.stringify(BChain2.getBlockByID(id)));

});


app.post('/api/addblock', (req , res) =>{

    const BChain2 = new bs.BlockChain();

    res.send(JSON.stringify(BChain2.addBlock));


});


app.listen(port,()=> console.log("I am alive"));
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-04-04 06:56:27

您不通过api向块链添加任何块,您向api端点发出请求,块链将挖掘块。我的意思是你不发送任何数据。为了添加某些内容,您可以发出一个"POST“请求,但是在本例中,您向端点发出一个get请求。

我认为你的做法是错误的。因为您定义了块类和块链类。这些是不同的类,但是挖掘是块链中的一种方法。由于Blockchain类的每个实例都有此方法,所以最好将其放在porototype中。

代码语言:javascript
复制
    Blockchain.prototype.createNewBlock=function(){}

想想看,“发条链”是一本有无限页的笔记本电脑。所有页面都是相同大小的,您可以在页面中记录事务。填充页面后,在传递到下一个空白页之前,您必须安全地签名。这个签名称为散列。您接受最后一个块的散列,事务在页面内,这个页面的现在是工作的证明,然后在sha256函数中创建一个十六进制的64个哈希字符。由于您对页面进行了安全签名,因此您需要为该页面编写一个标签,其中包含以下属性: index、nonce、previousBlockHash、currentHash、时间戳和事务。一旦完成,您可以将其添加到链中,因此您应该在Blockchain类中有一个属性来跟踪这些块。

代码语言:javascript
复制
  this.chain = [];//everytime you create a new block, you push them here

您应该在您的区块链中有一系列事务。

代码语言:javascript
复制
          this.pendingTransactions = [];

然后,在创建新事务时,应使用新事务填充此数组。您还需要创建一个用于创建事务的原型方法。

创建块方法:

代码语言:javascript
复制
Blockchain.prototype.createNewBlock = function(nonce, previousBlockHash, hash) {
  const newBlock = {
    index: this.chain.length + 1,//
    timestamp: Date.now(),
    transactions: this.pendingTransactions,
    nonce: nonce,
    hash: hash,
    previousBlockHash: previousBlockHash
  };
  //after a block is hashed, we cleared up the pendingTransactions[] for the new block 
  this.pendingTransactions = [];
  this.chain.push(newBlock);
  return newBlock;
};

在创建了该块之后,您需要创建一个端点来这个块。

代码语言:javascript
复制
app.get("/mine", (req, res) => {
  const lastBlock = blockchain.getLastBlock();// this.chain[this.chain.length - 1]
  const previousBlockHash = lastBlock["hash"];
  const currentBlockData = {
    transactions: blockchain.pendingTransactions,
    index: lastBlock["index"] + 1
  };
  const nonce = blockchain.proofOfWork(previousBlockHash, currentBlockData);//based on your algorithm find the nonce
  const blockHash = blockchain.hashBlock(
    previousBlockHash,
    currentBlockData,
    nonce
  );

  blockchain.createNewTransaction(6.25, "00", "address of the miner");// you need to reward the miner so create a new transaction
  const newBlock = blockchain.createNewBlock(nonce, previousBlockHash, blockHash);

  res.send({ note: "NEW BLOCK IS CREATED", blocks: newBlock });
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60814329

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档