Skip to content
This repository has been archived by the owner on Jun 17, 2022. It is now read-only.

Commit

Permalink
update state.json atomically
Browse files Browse the repository at this point in the history
  • Loading branch information
keppel committed Feb 13, 2019
1 parent e4085a1 commit 4102f55
Showing 1 changed file with 31 additions and 31 deletions.
62 changes: 31 additions & 31 deletions src/abci-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,23 @@ export default function createABCIServer(
let stateFilePath = join(lotionAppHome, 'state.json')
let height = 0
let abciServer = createServer({
info(request) {
return new Promise(async (resolve, reject) => {
await fs.ensureFile(stateFilePath)
try {
let stateFile = djson.parse(await fs.readFile(stateFilePath, 'utf8'))
let rootHash = createHash('sha256')
.update(djson.stringify(stateFile.state))
.digest()
async info(request) {
let stateFileExists = await fs.pathExists(stateFilePath)
if (stateFileExists) {
let stateFile = djson.parse(await fs.readFile(stateFilePath, 'utf8'))
let rootHash = createHash('sha256')
.update(djson.stringify(stateFile.state))
.digest()

stateMachine.initialize(stateFile.state, stateFile.context, true)
height = stateFile.height
resolve({
lastBlockAppHash: rootHash,
lastBlockHeight: stateFile.height
})
} catch (e) {
resolve({})
stateMachine.initialize(stateFile.state, stateFile.context, true)
height = stateFile.height
return {
lastBlockAppHash: rootHash,
lastBlockHeight: stateFile.height
}
})
} else {
return {}
}
},

deliverTx(request) {
Expand Down Expand Up @@ -85,20 +83,22 @@ export default function createABCIServer(
validatorUpdates
}
},
commit() {
return new Promise(async (resolve, reject) => {
let data = stateMachine.commit()
height++
await fs.writeFile(
stateFilePath,
djson.stringify({
state: stateMachine.query(),
height: height,
context: stateMachine.context()
})
)
resolve({ data: Buffer.from(data, 'hex') })
})
async commit() {
let data = stateMachine.commit()
height++
let newStateFilePath = join(lotionAppHome, `state-${height}.json`)
let context = Object.assign({}, stateMachine.context())
delete context.rootState
await fs.writeFile(
newStateFilePath,
djson.stringify({
context,
state: stateMachine.query(),
height: height
})
)
await fs.move(newStateFilePath, stateFilePath, { overwrite: true })
return { data: Buffer.from(data, 'hex') }
},
initChain(request) {
/**
Expand Down

0 comments on commit 4102f55

Please sign in to comment.