Giter Site home page Giter Site logo

js-ipns's Introduction

ipns

ipfs.tech Discuss codecov CI

IPNS Record definitions

Table of contents

Install

$ npm i ipns

Browser <script> tag

Loading this module through a script tag will make it's exports available as Ipns in the global namespace.

<script src="https://unpkg.com/ipns/dist/index.min.js"></script>

This module contains all the necessary code for creating, understanding and validating IPNS records.

Usage

Create record

import * as ipns from 'ipns'

const ipnsRecord = await ipns.create(privateKey, value, sequenceNumber, lifetime)

Validate record

import * as ipns from 'ipns'

await ipns.validate(publicKey, marshalledData)
// if no error thrown, the record is valid

Embed public key to record

import * as ipns from 'ipns'

const ipnsRecordWithEmbeddedPublicKey = await ipns.embedPublicKey(publicKey, ipnsRecord)

Extract public key from record

import * as ipns from 'ipns'

const publicKey = await ipns.extractPublicKey(peerId, ipnsRecord)

Datastore key

import * as ipns from 'ipns'

ipns.getLocalKey(peerId)

Returns a key to be used for storing the IPNS record locally, that is:

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

Marshal data with proto buffer

import * as ipns from 'ipns'

const ipnsRecord = await ipns.create(privateKey, value, sequenceNumber, lifetime)
// ...
const marshalledData = ipns.marshal(ipnsRecord)
// ...

Returns the record data serialized.

Unmarshal data from proto buffer

import * as ipns from 'ipns'

const ipnsRecord = ipns.unmarshal(storedData)

Returns the IPNSRecord after being deserialized.

Validator

import * as ipns from 'ipns'

const validator = ipns.validator

Contains an object with validate (marshalledData, key) and select (dataA, dataB) functions.

The validate async function aims to verify if an IPNS record is valid. First the record is unmarshalled, then the public key is obtained and finally the record is validated (signatureV2 of CBOR data is verified).

The select function is responsible for deciding which IPNS record is the best (newer) between two records. Both records are unmarshalled and their sequence numbers are compared. If the first record provided is the newer, the operation result will be 0, otherwise the operation result will be 1.

API

Create record

ipns.create(privateKey, value, sequenceNumber, lifetime, options)

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

  • privateKey (PrivateKey): key to be used for cryptographic operations.
  • value (string): IPFS path of the object to be published.
  • sequenceNumber (Number): number representing the current version of the record.
  • lifetime (Number): lifetime of the record (in milliseconds).
  • options (CreateOptions): additional creation options.

Returns a Promise that resolves to an object with a IPNSRecord.

Validate record

ipns.validate(publicKey, ipnsRecord)

Validate an IPNS record previously stored in a protocol buffer.

  • publicKey (PublicKey): key to be used for cryptographic operations.
  • ipnsRecord (IPNSRecord): IPNS record (obtained using the create function).

Returns a Promise, which may be rejected if the validation was not successful.

Marshal data with proto buffer

const marshalledData = ipns.marshal(ipnsRecord)

Returns the serialized IPNS record.

  • ipnsRecord (IPNSRecord): ipns record (obtained using the create function).

Unmarshal data from proto buffer

const data = ipns.unmarshal(storedData)

Returns a IPNSRecord after being serialized.

  • storedData (Uint8Array): ipns record serialized.

Extract public key from record

const publicKey = await ipns.extractPublicKey(peerId, ipnsRecord)

Extract a public key from an IPNS record.

  • peerId (PeerId): peer identifier object.
  • ipnsRecord (IPNSRecord): ipns record (obtained using the create function).

Returns a Promise which resolves to public key (PublicKey ): may be used for cryptographic operations.

Namespace

Namespace constants for records.

ipns.namespace

// '/ipns/'
ipns.namespaceLength

// 6

API Docs

License

Licensed under either of

Contribute

Contributions welcome! Please check out the issues.

Also see our contributing document for more information on how we work, and about contributing in general.

Please be aware that all interactions related to this repo are subject to the IPFS Code of Conduct.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

js-ipns's People

Contributors

2color avatar achingbrain avatar alanshaw avatar dependabot-preview[bot] avatar dependabot[bot] avatar dirkmc avatar eordano avatar fsdiogo avatar hacdias avatar hsanjuan avatar hugomrdias avatar iiska avatar ipfs-mgmt-read-write[bot] avatar jacobheun avatar jtsmedley avatar lidel avatar mr0grog avatar semantic-release-bot avatar stebalien avatar stensonb avatar swedneck avatar vasco-santos avatar web-flow avatar web3-bot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

js-ipns's Issues

Test failures

I see this intermittent problem very, very often in CI:

ipfs:   ipns-pubsub
ipfs: wait for republish as we can receive the republish message first
ipfs:     ✓ should get enabled state of pubsub
ipfs:     1) should publish the received record to a go node and a js subscriber should receive it
ipfs: Error: Timeout stopping go node. Process 7773 will be force killed now.
ipfs:     at Timeout.setTimeout [as _onTimeout] (/Users/travis/build/ipfs/js-ipfs/packages/ipfs/node_modules/ipfs-interop/node_modules/ipfsd-ctl/src/ipfsd-daemon.js:243:23)
ipfs:     at ontimeout (timers.js:436:11)
ipfs:     at tryOnTimeout (timers.js:300:5)
ipfs:     at listOnTimeout (timers.js:263:5)
ipfs:     at Timer.processTimers (timers.js:223:10)
ipfs:   1 passing (1m)
ipfs:   1 failing
ipfs:   1) ipns-pubsub
ipfs:        should publish the received record to a go node and a js subscriber should receive it:
ipfs:      HTTPError: failed to find any peer in table
ipfs:       at Object.errorHandler [as handleError] (/Users/travis/build/ipfs/js-ipfs/packages/ipfs-http-client/src/lib/core.js:67:15)
ipfs:       at async Client.fetch (/Users/travis/build/ipfs/js-ipfs/node_modules/ipfs-utils/src/http.js:145:9)
ipfs:       at async Object.publish (/Users/travis/build/ipfs/js-ipfs/packages/ipfs-http-client/src/name/publish.js:9:17)
ipfs:       at async subscribeToReceiveByPubsub (/Users/travis/build/ipfs/js-ipfs/packages/ipfs/node_modules/ipfs-interop/test/ipns-pubsub.js:103:16)
ipfs:       at async Context.<anonymous> (/Users/travis/build/ipfs/js-ipfs/packages/ipfs/node_modules/ipfs-interop/test/ipns-pubsub.js:73:5)

Any ideas what could be causing it? Are the tests not connecting the nodes together properly?

Can't create new ipns record

I try this code but my callback is not executed.

Why? may be i generate keys incorrectly?

const ipns = require('ipns');
const crypto = require('libp2p-crypto');


async function async(){
	const keys = await crypto.keys.generateKeyPair('RSA', 2048)

	ipns.create(keys, '/ipfs/QmNjRHSsT4Tj2nrvjaaGC1DmkQaV7Ec6gxZ34Qsrvqc2Zf', 0,'10000', (err, entryData) => {
		console.log(err)
		console.log(ipnsEntry);
	})

	
};

async()

Package require does not work

const ipns = require('ipns');

Throws an error:

Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in .../node_modules/ipns/package.json

Even if I tried to require specific script:

const ipnsValidator = require('ipns/src/validator');

It does not work:

Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './src/validator' is not defined by "exports" in .../node_modules/ipns/package.json

fails silently (given invalid pubkey)

const PeerId = require('peer-id')
const pid = await PeerId.create({ bits: 256, keyType: 'ed25519' })
const ipns = require('ipns')
ipns.create(pid.privKey, 'test value', 5, 100, (err, rec) => {
  console.error(err);
  console.log(rec);
})
// doesn't print anything or throw an error, just returns undefined :(

Throwing an 'unsupported key type' error or something would be way more helpful.

example doesn't work with PeerId

const PeerId = require('peer-id')
const ipns = require('ipns')

const pid = await PeerId.create({ bits: 2048, keyType: 'rsa' })

let value = 'test value 1'
let sequenceNumber = 42
let lifetime = 365 * 24 * 60 * 60 * 1000
let privateKey = pid.privKey

let record = await ipns.create(privateKey, value, sequenceNumber, lifetime)
console.log(record)

The above code will just hang forever when run with the most recent versions of js-peer-d and js-ipns.

Broken examples in README

Hi team,

I ran into some issues when attempting to use code from the examples:

$ node --version
v16.18.0
$ npm i ipns
import * as ipns from 'ipns'

const publicKey = ipns.extractPublicKey(peerId, ipnsEntry)
$ node testIpns.js 
file:///home/user/2023/February/tmp/testIpns.js:5
const publicKey = ipns.extractPublicKey(peerId, ipnsEntry)
                 ^

TypeError: ipns.extractPublicKey is not a function
    at file:///home/user/2023/February/tmp/testIpns.js:5:18
    at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:526:24)
    at async loadESM (node:internal/process/esm_loader:91:5)
    at async handleMainPromise (node:internal/modules/run_main:65:12)

I can only see the following exports:

[Module: null prototype] {
  create: [AsyncFunction: create],
  createWithExpiration: [AsyncFunction: createWithExpiration],
  getLocalKey: [Function: getLocalKey],
  marshal: [Function: marshal],
  namespace: '/ipns/',
  namespaceLength: 6,
  peerIdFromRoutingKey: [Function: peerIdFromRoutingKey],
  peerIdToRoutingKey: [Function: peerIdToRoutingKey],
  unmarshal: [Function: unmarshal]
}

I need to verify a couple of things regarding v2 signatures and this looked like the right library to use. Any pointers to get me going in the right direction?

Thanks!

Validator and validate code example do not work

Just run the following code and you will find the missing functions,

import * as ipns from 'ipns'
const validator = ipns.validator
console.log(validator)
console.log(Object.keys(ipns))

Result:

undefined
[
  'create',
  'createWithExpiration',
  'extractPublicKey',
  'getLocalKey',
  'marshal',
  'namespace',
  'namespaceLength',
  'peerIdFromRoutingKey',
  'peerIdToRoutingKey',
  'unmarshal'
]

Generating IPNS ID with IPFS hash

Hello, I know this is a pretty basic and dumb question but how do i actually generate an IPFS ID from my IPFS hash using this package? Would really appreciate if someone can help me since i tried to read the documentation but i failed to comprehend any of it.

bug: nanoseconds

Nanoseconds are calculated incorrectly. See ipfs/helia-verified-fetch#19 (comment) for more details. Basically,

Some proofs (copy and paste into dev console):

  • nanoseconds are 1e9, or "One billionth of one second".
    • BigInt(1)/*<s>*/ * BigInt(1e9)/*<ns>*/ === (1000000000n)/*<ns>*/ /* 1,000,000,000/*<ns>*/
    • 1000000000/*<ns>*/ * 1e-9/*<ns-to-s>*/ === 1
  • milliseconds are "1e6" or "One millionth of one second"
    • BigInt(1)/*<s>*/ * BigInt(1e6)/*<ms>*/ === 1000000n/*<ms>*/ /* === 1,000,000/*<ms>*/
    • 1000000/*<ms>*/ * 1e-6/*<ms-to-s>*/ === 1
  • nanoseconds are 1e6 or "One millionth of one millisecond"
    • BigInt(1)/*<ms>*/ * BigInt(1e6)/*<ns>*/ === 1000000n/*<ns>*/ /* === 1,000,000/*<ms>*/
    • 1000000/*<ns>*/ * 1e-6/*<ns-to-ms>*/ === 1

const lifetimeNs = (BigInt(ms) * BigInt(100000)) + BigInt(ns ?? '0')
creates lifeTimeNs as:

function lifeTimeNs(ms, ns) {
    // BigInt(100000) === BigInt(1e5)
    return (BigInt(ms) * BigInt(100000)) + BigInt(ns ?? '0')
}
// should match BigInt(1)/*<ms>*/ * BigInt(1e6)/*<ns>*/ === 1000000n/*<ns>*/
lifeTimeNs(1) === BigInt(1e6) // false, 
// returns `100000n` instead of `1000000n`

references:

Quick question

Just going to jump straight in here (x, u)
booby S
1:don't see how you could restrict android like seriously who, what originally branded coke-a-cola so what's wrong with Huawei?
2: seems poor old mate is getting raw end of the bamboo across the knuckles whilst strapped to the water tourcher chamber little rude this day N age?
3: simple work around really you won the moon race what's the hold up with pride in the computer part's manufacturers USA yikes you trying to cap the planet in record time or just a bunch of tooth picks with the ends cut off?
::I'd proudly sublet my pager to China after all don't they already have the equipment set-up for reproduction or have I simply crossed mi red/green wires up here made in Taiwan???.
#&look haz <shit struth do you really have to stumble into the electronic fence twice to feel the sensation of SOMETHING WENT WRONG

FOR THE LIVE OF GOD Could someone head over withv a couple cold beers and poor a goog head and finish talking about borrowed time.
I'm still trying to get this stupid horse with no name to drink at the same watering hole in peace coz ya know innovation leaps and bounds (<x indent "a map cord" %idea-any >u index "what the hell marshmallow man sorry about that didn't think stay puff could do Hartman.

Screws up bit of paper with scribbles well done champ/.
~inn created by [blank.namespace] simply no one to blame ice man 🤦‍♂️could have told me it melts?

Supremacy aid look after that brownie "not like you could find a chest to pin it on." 🧸

Philosophy of the day=
You can reshape turd still crap best leave it to its own discretion (need2knowBASES(doesn't need to know)) R'P when left alone the mystery bigins
D'Souza D'Arcy D'Angelo. D'ADERO glitch

`sys httml//boot/Huawei/parse/GooglePlay.com

0000
Gee golly gosh apologize for fate crashing your party 3!$

feature request: support extensible data fields

I would like to add support for extensible data to this implementation of the IPNS record.

This could be done by:

  1. adding an optional extensibleData field to CreateOptions.
  2. adding an optional parameter extensibleData to createCborData.
  3. inside of createCborData, merge extensibleData the data object.
  4. add tests and documentation

It's not necessary to change types or add generics to the record type. Users of this feature would simply have to decode IPNSRecord.data to read any extensible fields.

Code got stuck on `ipns.create` method

Environment:
node: v10.16.3
npm: v6.9.0
yarn: 1.19.1

Code:

const entity = await ipns.create(privateKey, cid.toString(), 0, 1000000);
console.log(entity); // <--- this code is not reachable 

No exception, nothing at all. Just stuck.

[Error] "callback is required" when using IPFS private key

js-ipfs version: 0.37.0.rc-0 (and master, as of 8/1/19)
js-ipns version: 0.6.0

const node = new IPFS()
// ... much later, after everything is set up ...
ipns.create(node._peerInfo.id._privKey, value, sequenceNumber, lifetime)

results in:

Error: record signature creation failed: callback is required

I investigated a bit and suspect this is happening because js-ipfs has not yet transitioned to the new async/await version of peer-id (0.13.x), which means the exported private key's sign function expects a callback, but js-inps expects a newer version with promises.

I've tried the simple solution of just incrementing the peer-id version in js-ipfs, and it built but could not successfully start the node (not sure why, there were no errors... it just hung).

Not sure where to go from here, let me know what I can do to help.

Too many dependencies

For a fairly simple system, this has too many dependencies. It would be cool to reduce them as much as possible...

Publish to network - example

Hi thanks for the great repo.
I'm using the base of the repo to build an application that lets users publish data to IPNS, using their metamask to sign.

I was wondering if you could help me answer the following:

  1. Why does the IPNS entry data require two signatures?

  2. Once I have created an IPNS entry record how do I send this entry to the network?
    Assuming I'm running the js-ipfs module in the browser; is there an easy way to publish a custom signed entry?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.