Skip to content

Commit

Permalink
fix: 🐛 Fix propose error because of id maxlength 64 to 128
Browse files Browse the repository at this point in the history
  • Loading branch information
limsbase committed Sep 3, 2020
1 parent 44ff7e6 commit 3152636
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 31 deletions.
37 changes: 22 additions & 15 deletions packages/peer/src/kernal/block/block.js
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,7 @@ class Block {
* @param {*} votes
*/
async receiveNewBlock (block, votes) {
if (this.runtime.state !== runtimeState.Ready) {
if (this.runtime.state !== runtimeState.Ready || !this.runtime.loaded) {
return
}

Expand Down Expand Up @@ -392,12 +392,14 @@ class Block {
}

async receiveVotes (votes) {
this.logger.debug('Receive votes start')
if (this.runtime.state !== runtimeState.Ready) {
return
}

this.sequence.add(async (cb) => {
const totalVotes = this.runtime.consensus.addPendingVotes(votes)

if (totalVotes && totalVotes.signatures) {
this.logger.debug(`receive new votes, total votes number ${totalVotes.signatures.length}`)
}
Expand All @@ -417,7 +419,7 @@ class Block {
}
}

this.logger.log(`receiveVotes: ${id} height: ${height} round: ${await this.runtime.round.getRound(height)} slot: ${this.runtime.slot.getSlotNumber(block.timestamp)} reward: ${block.reward}`)
this.logger.info(`receiveVotes: ${id} height: ${height} round: ${await this.runtime.round.getRound(height)} slot: ${this.runtime.slot.getSlotNumber(block.timestamp)} reward: ${block.reward}`)
}

cb()
Expand All @@ -429,6 +431,7 @@ class Block {
* @param {*} propose
*/
async receiveNewPropose (propose) {
this.logger.debug('receiveNewPropose start.')
if (this.runtime.state !== runtimeState.Ready) {
return
}
Expand All @@ -440,7 +443,6 @@ class Block {

await new Promise((resolve, reject) => {
this.sequence.add(async cb => {
// if (this._lastPropose && this._lastPropose.height === propose.height &&
if (this._lastPropose && bignum.isEqualTo(this._lastPropose.height, propose.height) &&
this._lastPropose.generator_public_key === propose.generator_public_key &&
this._lastPropose.id !== propose.id) {
Expand Down Expand Up @@ -478,7 +480,6 @@ class Block {
const activeKeypairs = await this.runtime.delegate.getActiveDelegateKeypairs(propose.height)
if (activeKeypairs && activeKeypairs.length > 0) {
const votes = this.runtime.consensus.createVotes(activeKeypairs, propose)

this.logger.debug(`send votes height ${votes.height} id ${votes.id} sigatures ${votes.signatures.length}`)

const replyData = {
Expand Down Expand Up @@ -506,25 +507,34 @@ class Block {
}

// 向提议请求节点回复本机授权
let res
setImmediate(async () => {
try {
await this.runtime.peer.request(replyData)
res = await this.runtime.peer.request(replyData)
if (res.body.success === false) {
this.logger.debug(`Replay propose request fail ${JSON.stringify(res.body.message)}.`)
}
} catch (err) {
this.logger.error(`Replay propose request failed: ${system.getErrorMsg(err)}`)
if (err) {
this.logger.error(`Replay propose request failed: ${system.getErrorMsg(err)}`)
}
}
})

this._lastVoteTime = Date.now()
this._lastPropose = propose
}
} catch (err) {
this.logger.error(`onReceivePropose error: ${err}`)
this.logger.error(`Receive propose fail, ${err}`)
cb(err)
}

this.logger.debug('onReceivePropose finished')

cb()
}, () => {
}, (err) => {
if (err) {
reject(err)
}
this.logger.debug('onReceivePropose finished')
resolve()
})
})
Expand Down Expand Up @@ -648,15 +658,13 @@ class Block {
await doApplyBlock()
} catch (err) {
this.logger.error(`Failed to apply block 1: ${err}`)
// cb(`Failed to apply block: ${err}`) // TODO: 2020.8.31
}

const redoTrs = unconfirmedTrs.filter((item) => !applyedTrsIdSet.has(item.id))
try {
await this.runtime.transaction.receiveTransactions(redoTrs)
} catch (err) {
this.logger.error('Failed to redo unconfirmed transactions', err)
cb(`Failed to redo unconfirmed transactions: ${err}`) // TODO: 2020.8.30
}

cb()
Expand Down Expand Up @@ -851,6 +859,7 @@ class Block {
throw new Error('DDN is preparing')
}

if (!block.transactions) block.transactions = []
try {
block = await this.objectNormalize(block)
} catch (e) {
Expand Down Expand Up @@ -921,7 +930,6 @@ class Block {
publicKey: transaction.senderPublicKey
})

// transaction.id = await this.runtime.transaction.getId(transaction); // 2020.5.18
transaction.id = await DdnCrypto.getId(transaction) // 2020.5.18
transaction.block_id = block.id // wxm block database

Expand All @@ -948,6 +956,7 @@ class Block {
try {
await this.applyBlock(block, votes, broadcast, save)
} catch (err) {
this.logger.error(`Failed to apply block: ${err}`)
return reject(err)
}

Expand Down Expand Up @@ -1045,9 +1054,7 @@ class Block {
}

this.runtime.consensus.setPendingBlock(block)

this.runtime.consensus.addPendingVotes(localVotes)

this._proposeCache[propose.hash] = true

setImmediate(async () => {
Expand Down
18 changes: 7 additions & 11 deletions packages/peer/src/kernal/consensus/consensus.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import ByteBuffer from 'bytebuffer'
import assert from 'assert'
import ip from 'ip'
import { nacl } from '@ddn/crypto'
import { nacl, createHash } from '@ddn/crypto'
import { bignum } from '@ddn/utils'

let _singleton
Expand Down Expand Up @@ -49,9 +49,7 @@ class Consensus {

bytes.flip()

// fixme: DdnCrypto.createHash 返回的是 buffer 是不对的
// return DdnCrypto.createHash(bytes.toBuffer())
return nacl.hash(bytes.toBuffer())
return createHash(bytes.toBuffer())
}

async createPropose (keypair, { generator_public_key, height, id, timestamp }, address) {
Expand All @@ -65,7 +63,8 @@ class Consensus {
}
const hash = this.getProposeHash(propose)
propose.hash = hash.toString('hex')
propose.signature = nacl.sign.detached(hash, Buffer.from(keypair.privateKey, 'hex'))
// propose.signature = nacl.sign.detached(hash, Buffer.from(keypair.privateKey, 'hex'))
propose.signature = Buffer.from(nacl.sign.detached(hash, Buffer.from(keypair.privateKey, 'hex'))).toString('hex')
return propose
}

Expand Down Expand Up @@ -99,7 +98,6 @@ class Consensus {
}

addPendingVotes ({ height, id, signatures }) {
// if (!this._pendingBlock || this._pendingBlock.height !== height || this._pendingBlock.id !== id) {
if (!this._pendingBlock || !bignum.isEqualTo(this._pendingBlock.height, height) || this._pendingBlock.id !== id) {
return this._pendingVotes
}
Expand Down Expand Up @@ -167,13 +165,11 @@ class Consensus {
getVoteHash (height, id) {
const bytes = new ByteBuffer()

// Bignum update bytes.writeLong(height);
bytes.writeString(`${height}`)
bytes.writeString(id)

bytes.flip()
// fixme: DdnCrypto.createHash 返回的是 buffer 是不对的
return nacl.hash(bytes.toBuffer())
return createHash(bytes.toBuffer())
}

/**
Expand All @@ -192,7 +188,7 @@ class Consensus {
keypairs.forEach(el => {
votes.signatures.push({
key: el.publicKey.toString('hex'),
sig: nacl.sign.detached(hash, Buffer.from(el.privateKey, 'hex'))
sig: Buffer.from(nacl.sign.detached(hash, Buffer.from(el.privateKey, 'hex'))).toString('hex')
})
})

Expand All @@ -215,7 +211,7 @@ class Consensus {
* @param {*} votes
*/
hasEnoughVotes (votes) {
return votes && votes.signatures && (votes.signatures.length >= this.constants.voters) // (this.constants.delegates * 2 / 3)
return votes && votes.signatures && (votes.signatures.length >= this.constants.voters)
}

/**
Expand Down
1 change: 1 addition & 0 deletions packages/peer/src/kernal/peer/peer.js
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,7 @@ class Peer {
* @param {*} timeoutSeconds 服务暂停时间(单位:秒)
*/
async changeState (pip, port, state, timeoutSeconds) {
// FIXME: 2020.9.3 白名单状态修改
// const isStaticPeer = this.config.peers.list.find(
// peer => peer.ip === ip.fromLong(pip) && peer.port === port
// )
Expand Down
12 changes: 7 additions & 5 deletions packages/peer/src/network/service/peer/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ class PeerService {
},
id: {
type: 'string',
maxLength: 64
maxLength: 128
},
timestamp: {
type: 'integer'
Expand Down Expand Up @@ -176,7 +176,7 @@ class PeerService {
if (validateErrors) {
return {
success: false,
error: `Schema validation error: ${validateErrors[0].schemaPath} ${validateErrors[0].message}`
error: `Invalid parameters: : ${validateErrors[0].schemaPath} ${validateErrors[0].message}`
}
}

Expand All @@ -199,22 +199,24 @@ class PeerService {
},
id: {
type: 'string',
maxLength: 64
maxLength: 128
},
signatures: {
type: 'array',
minLength: 1,
maxLength: 101
maxLength: this.constants.delegates // 101
}
},
required: ['height', 'id', 'signatures']
},
body
)

// Todo: 2020.9.3 请求本接口的方法应该对 success 做个判断,或者改成 throw
if (validateErrors) {
return {
success: false,
error: `Schema validation error: ${validateErrors[0].schemaPath} ${validateErrors[0].message}`
error: `Invalid parameters: : ${validateErrors[0].schemaPath} ${validateErrors[0].message}`
}
}

Expand Down

0 comments on commit 3152636

Please sign in to comment.