Skip to content
This repository has been archived by the owner on Apr 6, 2020. It is now read-only.

Commit

Permalink
Factor out Blockchain#_lockUnlock
Browse files Browse the repository at this point in the history
  • Loading branch information
whymarrh committed Mar 7, 2019
1 parent 8686de0 commit ccd0af5
Showing 1 changed file with 21 additions and 57 deletions.
78 changes: 21 additions & 57 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -229,29 +229,13 @@ export default class Blockchain {
* Adds a block to the blockchain
*/
putBlock(block: object, cb: any, isGenesis?: any) {
const self = this;

// make sure init has completed
self._initLock.await(() => {
this._initLock.await(() => {
// perform put with mutex dance
lockUnlock((done: any) => {
self._putBlockOrHeader(block, done, isGenesis);
this._lockUnlock((done: any) => {
this._putBlockOrHeader(block, done, isGenesis);
}, cb);
});

// lock, call fn, unlock
function lockUnlock(fn: any, cb: any) {
// take lock
self._putSemaphore.take(function() {
// call fn
fn(function() {
// leave lock
self._putSemaphore.leave();
// exit
cb.apply(null, arguments);
});
});
}
}

/**
Expand All @@ -271,29 +255,13 @@ export default class Blockchain {
* Adds a header to the blockchain
*/
putHeader(header: object, cb: any) {
const self = this;

// make sure init has completed
self._initLock.await(() => {
this._initLock.await(() => {
// perform put with mutex dance
lockUnlock((done: any) => {
self._putBlockOrHeader(header, done);
this._lockUnlock((done: any) => {
this._putBlockOrHeader(header, done);
}, cb);
});

// lock, call fn, unlock
function lockUnlock(fn: any, cb: any) {
// take lock
self._putSemaphore.take(function() {
// call fn
fn(function() {
// leave lock
self._putSemaphore.leave();
// exit
cb.apply(null, arguments);
});
});
}
}

_putBlockOrHeader(item: any, cb: any, isGenesis?: any) {
Expand Down Expand Up @@ -728,29 +696,13 @@ export default class Blockchain {
* and any encountered heads are set to the parent block
*/
delBlock(blockHash: Buffer, cb: any) {
const self = this;

// make sure init has completed
self._initLock.await(() => {
this._initLock.await(() => {
// perform put with mutex dance
lockUnlock((done: boolean) => {
self._delBlock(blockHash, done);
this._lockUnlock((done: boolean) => {
this._delBlock(blockHash, done);
}, cb);
});

// lock, call fn, unlock
function lockUnlock(fn: any, cb: any) {
// take lock
self._putSemaphore.take(function() {
// call fn
fn(function() {
// leave lock
self._putSemaphore.leave();
// exit
cb.apply(null, arguments);
});
});
}
}

_delBlock(blockHash: any, cb: any) {
Expand Down Expand Up @@ -1057,4 +1009,16 @@ export default class Blockchain {
}
);
}

_lockUnlock(fn: any, cb: any) {
const self = this
this._putSemaphore.take(() => {
fn(after)

function after() {
self._putSemaphore.leave();
cb.apply(null, arguments)
}
})
}
}

0 comments on commit ccd0af5

Please sign in to comment.