Skip to content

feat: add decapsulateCode method #98

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 2 commits into from
Sep 10, 2019
Merged
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
28 changes: 28 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,34 @@ Multiaddr.prototype.decapsulate = function decapsulate (addr) {
return Multiaddr(s.slice(0, i))
}

/**
* A more reliable version of `decapsulate` if you are targeting a
* specific code, such as 421 (the `p2p` protocol code). The last index of the code
* will be removed from the `Multiaddr`, and a new instance will be returned.
* If the code is not present, the original `Multiaddr` is returned.
*
* @param {Number} code The code of the protocol to decapsulate from this Multiaddr
* @return {Multiaddr}
* @example
* const addr = Multiaddr('/ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC')
* // <Multiaddr 0400... - /ip4/0.0.0.0/tcp/8080/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC>
*
* addr.decapsulateCode(421).toString()
* // '/ip4/0.0.0.0/tcp/8080'
*
* Multiaddr('/ip4/127.0.0.1/tcp/8080').decapsulateCode(421).toString()
* // '/ip4/127.0.0.1/tcp/8080'
*/
Multiaddr.prototype.decapsulateCode = function decapsulateCode (code) {
const tuples = this.tuples()
for (let i = tuples.length - 1; i >= 0; i--) {
if (tuples[i][0] === code) {
return Multiaddr(codec.tuplesToBuffer(tuples.slice(0, i)))
}
}
return this
}

/**
* Extract the peerId if the multiaddr contains one
*
Expand Down
16 changes: 16 additions & 0 deletions test/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -598,6 +598,22 @@ describe('helpers', () => {
})
})

describe('.decapsulateCode', () => {
it('removes the last occurrence of the code from the multiaddr', () => {
const relayTCP = multiaddr('/ip4/0.0.0.0/tcp/8080')
const relay = relayTCP.encapsulate('/p2p/QmZR5a9AAXGqQF2ADqoDdGS8zvqv8n3Pag6TDDnTNMcFW6/p2p-circuit')
const target = multiaddr('/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC')
const original = relay.encapsulate(target)
expect(original.decapsulateCode(421)).to.eql(relay)
expect(relay.decapsulateCode(421)).to.eql(relayTCP)
})

it('ignores missing codes', () => {
const tcp = multiaddr('/ip4/0.0.0.0/tcp/8080')
expect(tcp.decapsulateCode(421)).to.eql(tcp)
})
})

describe('.equals', () => {
it('returns true for equal addresses', () => {
const addr1 = multiaddr('/ip4/192.168.0.1')
Expand Down