Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,9 @@ Open [config/default.json](config/default.json) and edit it with your settings:
- `rpcPort`
- `rpcUser`
- `rpcPassword`
- change authentication parameters (see [Authentication](#Authentication)):
- `enabled` which enables authentication checks on the api endpoints
- `jwtKey` the key used to generate the jwt

If you need to change the settings dynamically from the environment variables, you overwrite them using the environment variable *NODE_CONFIG*. Such as this:

Expand Down Expand Up @@ -132,6 +135,42 @@ Change any settings in the [docker-compose](docker-compose.yml) to fit your conf
$ docker-compose up -d
```

#### Initial Setup

Once the docker container is running, you will need to setup and configure your Miner ID by generating a Miner ID private key as well as setting up your [Validity Check Transaction output (VCTx)](https://github.com/bitcoin-sv-specs/brfc-minerid#323-key-design-decisions). You can do that using `docker exec`:

```console
$ docker exec -it <CONTAINER> bash

root@2623e1f4ed4e:/app#
```

Then run the cli commands to setup and configure the above:

```console
root@2623e1f4ed4e:/app# npm run cli -- generateminerid --name testMiner
```

```console
root@2623e1f4ed4e:/app# npm run cli -- generatevctx --name testMiner
```

If you are running on `livenet` (mainnet), follow the instructions to fund your VCTx.

## Authentication

This service uses [JWT tokens](https://tools.ietf.org/html/rfc7519) for authentication. The `authentication.jwtKey` [config](config/default.json) is used for all tokens. To revoke all tokens, change this key. To generate a new `jwtKey`, run the following script:

```console
node -e "console.log(require('crypto').randomBytes(32).toString('hex'));"
```

To generate a JTW token for a user of MinerId, run the `generate_jwt` npm command (you can also set the expiry time in the [generateJWT](config/generateJWT.js) file):

```console
$ npm run generate_jwt <USER_NAME>
```

## Testing

```console
Expand Down
55 changes: 40 additions & 15 deletions builder.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@ const config = require('config')
const fm = require('./utils/filemanager')
const { placeholderCB1 } = require('./services/extensions')
const coinbaseDocService = require('./services/coinbaseDocumentService')
const { authenticateToken } = require('./utils/authentication')
const bsv = require('bsv')

const app = express()
app.use(bodyParser.json())

app.get('/opreturn/:alias/:blockHeight([0-9]+)', async (req, res) => {
app.get('/opreturn/:alias/:blockHeight([0-9]+)', authenticateToken, async (req, res) => {
const { blockHeight, alias } = req.params

res.setHeader('Content-Type', 'text/plain')
Expand All @@ -27,15 +28,19 @@ app.get('/opreturn/:alias/:blockHeight([0-9]+)', async (req, res) => {
}

try {
const opReturn = await coinbaseDocService.createMinerIdOpReturn(blockHeight, alias)
const opReturn = await coinbaseDocService.createMinerIdOpReturn(
blockHeight,
alias
)
res.send(opReturn)
} catch (err) {
res.status(500).send(`Internal error: ${err.message}`)
console.warn(`Internal error: ${err.message}`)
}
})
}
)

app.post('/coinbase2', async (req, res) => {
app.post('/coinbase2', authenticateToken, async (req, res) => {
const { blockHeight, alias, coinbase2, jobData } = req.body

res.setHeader('Content-Type', 'text/plain')
Expand Down Expand Up @@ -72,23 +77,33 @@ app.post('/coinbase2', async (req, res) => {

try {
// try to create a BitCoin transaction using Coinbase 2
bsv.Transaction(Buffer.concat([Buffer.from(placeholderCB1, 'hex'), Buffer.from(coinbase2, 'hex')]))
bsv.Transaction(
Buffer.concat([
Buffer.from(placeholderCB1, 'hex'),
Buffer.from(coinbase2, 'hex')
])
)
} catch (error) {
res.status(422).send('Invalid Coinbase 2')
console.log('Bad request: invalid coinbase2: ', coinbase2)
return
}

try {
const cb2 = await coinbaseDocService.createNewCoinbase2(blockHeight, alias, coinbase2, jobData)
const cb2 = await coinbaseDocService.createNewCoinbase2(
blockHeight,
alias,
coinbase2,
jobData
)
res.send(cb2)
} catch (err) {
res.status(500).send(`Internal error:: ${err.message}`)
console.warn(`Internal error: ${err.message}`)
}
})

app.get('/opreturn/:alias/rotate', (req, res) => {
app.get('/opreturn/:alias/rotate', authenticateToken, (req, res) => {
res.setHeader('Content-Type', 'text/plain')

if (!fm.aliasExists(req.params.alias)) {
Expand All @@ -106,7 +121,7 @@ app.get('/opreturn/:alias/rotate', (req, res) => {
}
})

app.get('/minerid/:alias', (req, res) => {
app.get('/minerid/:alias', authenticateToken, (req, res) => {
res.setHeader('Content-Type', 'text/plain')

if (!fm.aliasExists(req.params.alias)) {
Expand All @@ -124,7 +139,7 @@ app.get('/minerid/:alias', (req, res) => {
}
})

app.get('/minerid/:alias/sign/:hash([0-9a-fA-F]+)', (req, res) => {
app.get('/minerid/:alias/sign/:hash([0-9a-fA-F]+)', authenticateToken, (req, res) => {
res.setHeader('Content-Type', 'text/plain')

if (!fm.aliasExists(req.params.alias)) {
Expand All @@ -140,15 +155,19 @@ app.get('/minerid/:alias/sign/:hash([0-9a-fA-F]+)', (req, res) => {
}

try {
const signature = coinbaseDocService.signWithCurrentMinerId(req.params.hash, req.params.alias)
const signature = coinbaseDocService.signWithCurrentMinerId(
req.params.hash,
req.params.alias
)
res.send(signature)
} catch (err) {
res.status(500).send(`Internal error: ${err.message}`)
console.warn(`Internal error: ${err.message}`)
}
})
}
)

app.get('/minerid/:alias/pksign/:hash([0-9a-fA-F]+)', (req, res) => {
app.get('/minerid/:alias/pksign/:hash([0-9a-fA-F]+)', authenticateToken, (req, res) => {
res.setHeader('Content-Type', 'application/json')

if (!fm.aliasExists(req.params.alias)) {
Expand All @@ -164,15 +183,21 @@ app.get('/minerid/:alias/pksign/:hash([0-9a-fA-F]+)', (req, res) => {
}

try {
const currentAlias = coinbaseDocService.getCurrentMinerId(req.params.alias)
const signature = coinbaseDocService.signWithCurrentMinerId(req.params.hash, req.params.alias)
const currentAlias = coinbaseDocService.getCurrentMinerId(
req.params.alias
)
const signature = coinbaseDocService.signWithCurrentMinerId(
req.params.hash,
req.params.alias
)

res.send({ publicKey: currentAlias, signature })
} catch (err) {
res.status(500).send(`Internal error: ${err.message}`)
console.warn(`Internal error: ${err.message}`)
}
})
}
)

app.listen(config.get('port'), () => {
console.log(`Server running on port ${config.get('port')}`)
Expand Down
4 changes: 4 additions & 0 deletions config/default.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,9 @@
"rpcPort": 18332,
"rpcUser": "bitcoin",
"rpcPassword": "bitcoin"
},
"authentication": {
"enabled": true,
"jwtKey": "e4ef52bbc43782bcbb1dc6ac11bdfe978abccecb180ebd90820ea850fd3ff245"
}
}
14 changes: 14 additions & 0 deletions config/generateJWT.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// pass argument to npm run generate_JWT to add a username

const jwt = require('jsonwebtoken')
const config = require('config')

function generateAccessToken (username) {
// return jwt.sign(username, config.jwtKey, { expiresIn: '1800s' })

return jwt.sign(username, config.get('authentication.jwtKey'))
}

const token = generateAccessToken({ username: process.argv.slice(2)[0] })

console.log(token)
94 changes: 92 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
"scripts": {
"start": "node builder.js",
"cli": "node cli.js",
"test": "mocha"
"test": "mocha",
"generate_jwt": "node config/generateJWT.js"
},
"author": "nChain Application Development Team",
"contributors": [
Expand All @@ -25,6 +26,7 @@
"command-line-usage": "^6.0.2",
"config": "^3.3.1",
"express": "^4.17.1",
"jsonwebtoken": "^8.5.1",
"request": "^2.88.2",
"request-promise": "^4.2.5"
},
Expand Down
2 changes: 1 addition & 1 deletion plugins/blockbind.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ function buildMerkleRootFromCoinbase (coinbaseHash, merkleBranches) {

merkleBranches.forEach(merkleBranch => {
merkleBranch = swapEndianness(Buffer.from(merkleBranch, 'hex')) // swap endianness before concatenating
let concat = Buffer.concat([res, merkleBranch])
const concat = Buffer.concat([res, merkleBranch])
res = bsv.crypto.Hash.sha256sha256(concat)
})

Expand Down
6 changes: 3 additions & 3 deletions test/coinbaseDocumentService.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -198,11 +198,11 @@ describe('Coinbase Document Services', function () {
beforeEach(() => {
mock({
[`${os.homedir()}/.minerid-client/unittest`]: {
'aliases': '[ { "name": "unittest_1" } ]',
'config': `{
aliases: '[ { "name": "unittest_1" } ]',
config: `{
"email": "testMiner@testDomain.com"
}`,
'vctx': `{
vctx: `{
"prv": "KxmBu7NFRxWsT6gcwBDCtthWnokPJhHDVajYAVvTwfucFKdMf1dP",
"txid": "6839008199026098cc78bf5f34c9a6bdf7a8009c9f019f8399c7ca1945b4a4ff"
}`
Expand Down
Loading