Skip to content

feat: initial implementation #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 29, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
12 changes: 6 additions & 6 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License
The MIT License (MIT)

Copyright (c) 2018 IPFS
Copyright (c) 2018 Protocol Labs, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand All @@ -9,13 +9,13 @@ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
85 changes: 72 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ This module contains all the necessary code for creating, understanding and vali
```js
const ipns = require('ipns')

ipns.create(privateKey, value, seqNumber, eol, (err, entryData) => {
ipns.create(privateKey, value, sequenceNumber, lifetime, (err, entryData) => {
// your code goes here
});
```
Expand Down Expand Up @@ -67,44 +67,82 @@ ipns.validate(publicKey, ipnsEntry, (err) => {
```js
const ipns = require('ipns')

ipns.getDatastoreKey(peerId);
ipns.getLocalKey(peerId);
```

Returns a key to be used for storing the ipns entry in the datastore according to the specs, that is:
Returns a key to be used for storing the ipns entry locally, that is:

```
/ipns/${base32(<HASH>)}
```

#### Marshal data with proto buffer

```js
const ipns = require('ipns')

ipns.create(privateKey, value, sequenceNumber, lifetime, (err, entryData) => {
// ...
const marshalledData = ipns.marshal(entryData)
// ...
});
```

Returns the entry data serialized.

#### Unmarshal data from proto buffer

```js
const ipns = require('ipns')

const data = ipns.unmarshal(storedData)
```

Returns the entry data structure after being serialized.

## API

#### Create record

```js

ipns.create(privateKey, value, sequenceNumber, eol, callback);
ipns.create(privateKey, value, sequenceNumber, lifetime, [callback]);
```

Create an IPNS record for being stored in a protocol buffer.

- `privateKey` (`PrivKey` RSA Instance): key to be used for cryptographic operations.
- `privateKey` (`PrivKey` [RSA Instance](https://github.com/libp2p/js-libp2p-crypto/blob/master/src/keys/rsa-class.js)): key to be used for cryptographic operations.
- `value` (string): ipfs path of the object to be published.
- `sequenceNumber` (Number): sequence number of the record.
- `eol` (string): end of life datetime of the record (according to RFC3339).
- `sequenceNumber` (Number): number representing the current version of the record.
- `lifetime` (string): lifetime of the record (in milliseconds).
- `callback` (function): operation result.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This needs documentation about the shape or class of the object that is returned, it's methods and properties.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

haha, still says (string) here, should it be a number now?


#### Create record
`callback` must follow `function (err, ipnsEntry) {}` signature, where `err` is an error if the operation was not successful. `ipnsEntry` is an object that contains the entry's properties, such as:

```js
{
value: '/ipfs/QmWEekX7EZLUd9VXRNMRXW3LXe4F6x7mB8oPxY5XLptrBq',
signature: Buffer,
validityType: 0,
validity: '2018-06-27T14:49:14.074000000Z',
sequence: 2
}
```

#### Validate record

```js

ipns.validate(publicKey, ipnsEntry, callback);
ipns.validate(publicKey, ipnsEntry, [callback]);
```

Create an IPNS record for being stored in a protocol buffer.
Validate an IPNS record previously stored in a protocol buffer.

- `publicKey` (`PubKey` RSA Instance): key to be used for cryptographic operations.
- `publicKey` (`PubKey` [RSA Instance](https://github.com/libp2p/js-libp2p-crypto/blob/master/src/keys/rsa-class.js)): key to be used for cryptographic operations.
- `ipnsEntry` (Object): ipns entry record (obtained using the create function).
- `callback` (function): operation result (if no error, validation successful).
- `callback` (function): operation result.

`callback` must follow `function (err) {}` signature, where `err` is an error if the operation was not successful. This way, if no error, the validation was successful.

#### Datastore key

Expand All @@ -116,6 +154,27 @@ Get a key for storing the ipns entry in the datastore.

- `peerId` (`Uint8Array`): peer identifier.

#### Marshal data with proto buffer

```js
const marshalledData = ipns.marshal(entryData)
});
```

Returns the entry data serialized.

- `entryData` (Object): ipns entry record (obtained using the create function).

#### Unmarshal data from proto buffer

```js
const data = ipns.unmarshal(storedData)
```

Returns the entry data structure after being serialized.

- `storedData` (Buffer): ipns entry record serialized.

## Contribute

Feel free to join in. All welcome. Open an [issue](https://github.com/ipfs/js-ipns/issues)!
Expand All @@ -126,4 +185,4 @@ This repository falls under the IPFS [Code of Conduct](https://github.com/ipfs/c

## License

[MIT](LICENSE)
Copyright (c) Protocol Labs, Inc. under the **MIT**. See [MIT](./LICENSE) for details.
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,11 @@
},
"homepage": "https://github.com/ipfs/js-ipns#readme",
"dependencies": {
"base32-encode": "^1.0.0",
"base32-encode": "^1.1.0",
"big.js": "^5.1.2",
"debug": "^3.1.0",
"left-pad": "^1.3.0",
"nano-date": "^2.1.0",
"protons": "^1.0.1"
},
"devDependencies": {
Expand Down
2 changes: 2 additions & 0 deletions src/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,6 @@

exports.ERR_IPNS_EXPIRED_RECORD = 'ERR_IPNS_EXPIRED_RECORD'
exports.ERR_UNRECOGNIZED_VALIDITY = 'ERR_UNRECOGNIZED_VALIDITY'
exports.ERR_SIGNATURE_CREATION = 'ERR_SIGNATURE_CREATION'
exports.ERR_SIGNATURE_VERIFICATION = 'ERR_SIGNATURE_VERIFICATION'
exports.ERR_UNRECOGNIZED_FORMAT = 'ERR_UNRECOGNIZED_FORMAT'
68 changes: 42 additions & 26 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,39 +1,51 @@
'use strict'

const base32Encode = require('base32-encode')
const Big = require('big.js')
const NanoDate = require('nano-date').default

const debug = require('debug')
const log = debug('jsipns')
log.error = debug('jsipns:error')

const ipnsEntryProto = require('./pb/ipns.proto')
const { parseRFC3339 } = require('./utils')
const ERRORS = require('./errors')

/**
* Creates a new ipns entry and signs it with the given private key.
* The ipns entry validity should follow the [RFC3339]{@link https://www.ietf.org/rfc/rfc3339.txt} with nanoseconds precision.
* Note: This function does not embed the public key. If you want to do that, use `EmbedPublicKey`.
*
* @param {Object} privateKey private key for signing the record.
* @param {string} value value to be stored in the record.
* @param {number} seq sequence number of the record.
* @param {string} eol end of life datetime of the record.
* @param {function(Error)} [callback]
* @returns {Promise|void}
* @param {number} seq number representing the current version of the record.
* @param {string} lifetime lifetime of the record (in milliseconds).
* @param {function(Error, entry)} [callback]
* @returns {function(Error, entry)} callback
*/
const create = (privateKey, value, seq, eol, callback) => {
const validity = eol.toISOString()
const create = (privateKey, value, seq, lifetime, callback) => {
// Calculate eol with nanoseconds precision
const bnLifetime = new Big(lifetime)
const bnCurrentDate = new Big(new NanoDate())
const bnEol = bnCurrentDate.plus(bnLifetime).times('10e+6')
const nanoDateEol = new NanoDate(bnEol.toString())

// Validity in ISOString with nanoseconds precision and validity type EOL
const isoValidity = nanoDateEol.toISOStringFull()
const validityType = ipnsEntryProto.ValidityType.EOL

sign(privateKey, value, validityType, validity, (error, signature) => {
sign(privateKey, value, validityType, isoValidity, (error, signature) => {
if (error) {
log.error(error)
return callback(error)
log.error('record signature creation failed')
return callback(Object.assign(new Error('record signature verification failed'), { code: ERRORS.ERR_SIGNATURE_CREATION }))
}

const entry = {
value: value,
signature: signature, // TODO confirm format compliance with go-ipfs
validityType: validityType,
validity: validity,
validity: isoValidity,
sequence: seq
}

Expand All @@ -48,7 +60,7 @@ const create = (privateKey, value, seq, eol, callback) => {
* @param {Object} publicKey public key for validating the record.
* @param {Object} entry ipns entry record.
* @param {function(Error)} [callback]
* @returns {Promise|void}
* @returns {function(Error)} callback
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isn't this @return {Void} also?

*/
const validate = (publicKey, entry, callback) => {
const { value, validityType, validity } = entry
Expand All @@ -63,7 +75,14 @@ const validate = (publicKey, entry, callback) => {

// Validate according to the validity type
if (validityType === ipnsEntryProto.ValidityType.EOL) {
const validityDate = Date.parse(validity.toString())
let validityDate

try {
validityDate = parseRFC3339(validity.toString())
} catch (e) {
log.error('unrecognized validity format (not an rfc3339 format)')
return callback(Object.assign(new Error('unrecognized validity format (not an rfc3339 format)'), { code: ERRORS.ERR_UNRECOGNIZED_FORMAT }))
}

if (validityDate < Date.now()) {
log.error('record has expired')
Expand All @@ -85,10 +104,10 @@ const validate = (publicKey, entry, callback) => {
* @param {Object} publicKey public key for validating the record.
* @param {Object} entry ipns entry record.
* @param {function(Error)} [callback]
* @returns {Promise|void}
* @return {Void}
*/
const embedPublicKey = (publicKey, entry, callback) => {
return callback(new Error('not implemented yet'))
callback(new Error('not implemented yet'))
}

/**
Expand All @@ -97,33 +116,30 @@ const embedPublicKey = (publicKey, entry, callback) => {
* @param {Object} peerId peer identifier object.
* @param {Object} entry ipns entry record.
* @param {function(Error)} [callback]
* @returns {Promise|void}
* @return {Void}
*/
const extractPublicKey = (peerId, entry, callback) => {
return callback(new Error('not implemented yet'))
callback(new Error('not implemented yet'))
}

// rawStdEncoding as go
// TODO Remove once resolved
// Created PR for allowing this inside base32-encode https://github.com/LinusU/base32-encode/issues/2
const regex = new RegExp('=', 'g')
const rawStdEncoding = (key) => base32Encode(key, 'RFC4648').replace(regex, '')
// rawStdEncoding with RFC4648
const rawStdEncoding = (key) => base32Encode(key, 'RFC4648', { padding: false })

/**
* Get key for storing the record in the datastore.
* Get key for storing the record locally.
* Format: /ipns/${base32(<HASH>)}
*
* @param {Buffer} key peer identifier object.
* @returns {string}
*/
const getDatastoreKey = (key) => `/ipns/${rawStdEncoding(key)}`
const getLocalKey = (key) => `/ipns/${rawStdEncoding(key)}`

/**
* Get key for sharing the record in the routing mechanism.
* Format: ${base32(/ipns/<HASH>)}, ${base32(/pk/<HASH>)}
*
* @param {Buffer} key peer identifier object.
* @returns {string}
* @returns {Object} containgin the `nameKey` and the `ipnsKey`.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typo "containgin"

*/
const getIdKeys = (key) => {
const pkBuffer = Buffer.from('/pk/')
Expand Down Expand Up @@ -165,8 +181,8 @@ module.exports = {
embedPublicKey,
// extract public key from the record
extractPublicKey,
// get key for datastore
getDatastoreKey,
// get key for storing the entry locally
getLocalKey,
// get keys for routing
getIdKeys,
// marshal
Expand Down
56 changes: 56 additions & 0 deletions src/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
'use strict'

const leftPad = require('left-pad')

/**
* Convert a JavaScript date into an `RFC3339Nano` formatted
* string.
*
* @param {Date} time
* @returns {string}
*/
module.exports.toRFC3339 = (time) => {
const year = time.getUTCFullYear()
const month = leftPad(time.getUTCMonth() + 1, 2, '0')
const day = leftPad(time.getUTCDate(), 2, '0')
const hour = leftPad(time.getUTCHours(), 2, '0')
const minute = leftPad(time.getUTCMinutes(), 2, '0')
const seconds = leftPad(time.getUTCSeconds(), 2, '0')
const milliseconds = time.getUTCMilliseconds()
const nanoseconds = milliseconds * 1000 * 1000

return `${year}-${month}-${day}T${hour}:${minute}:${seconds}.${nanoseconds}Z`
}

/**
* Parses a date string formatted as `RFC3339Nano` into a
* JavaScript Date object.
*
* @param {string} time
* @returns {Date}
*/
module.exports.parseRFC3339 = (time) => {
const rfc3339Matcher = new RegExp(
// 2006-01-02T
'(\\d{4})-(\\d{2})-(\\d{2})T' +
// 15:04:05
'(\\d{2}):(\\d{2}):(\\d{2})' +
// .999999999Z
'\\.(\\d+)Z'
)
const m = String(time).trim().match(rfc3339Matcher)

if (!m) {
throw new Error('Invalid format')
}

const year = parseInt(m[1], 10)
const month = parseInt(m[2], 10) - 1
const date = parseInt(m[3], 10)
const hour = parseInt(m[4], 10)
const minute = parseInt(m[5], 10)
const second = parseInt(m[6], 10)
const millisecond = parseInt(m[7].slice(0, -6), 10)

return new Date(Date.UTC(year, month, date, hour, minute, second, millisecond))
}
Loading