Skip to content
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

Replace Buffer with Uint8Array in codec #363

Merged
merged 6 commits into from
Jun 4, 2024
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
7 changes: 1 addition & 6 deletions packages/walletconnect/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,7 @@ module.exports = {
index: path.resolve(__dirname, "dist", "cjs", "index.js"),
},
plugins: [
new webpack.SourceMapDevToolPlugin({ filename: "[file].map" }),
new webpack.ProvidePlugin({
// you must `npm install buffer` to use this.
Buffer: ['buffer', 'Buffer']
})
new webpack.SourceMapDevToolPlugin({ filename: "[file].map" })
],
module: {
rules: [
Expand All @@ -26,7 +22,6 @@ module.exports = {
extensions: [".tsx", ".ts", ".js"],
fallback: {
fs: false,
buffer: require.resolve('buffer'),
stream: require.resolve("stream-browserify"),
crypto: require.resolve("crypto-browserify"),
path: require.resolve("path-browserify")
Expand Down
1 change: 0 additions & 1 deletion packages/web3-wallet/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@
"@types/node": "^16.18.23",
"bip32": "3.1.0",
"bip39": "3.0.4",
"buffer": "^6.0.3",
"elliptic": "6.5.4",
"fs-extra": "10.0.1"
},
Expand Down
4 changes: 2 additions & 2 deletions packages/web3-wallet/src/noble-wrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ necc.utils.sha256Sync = (...messages: Uint8Array[]): Uint8Array => {
}

necc.utils.hmacSha256Sync = (key: Uint8Array, ...messages: Uint8Array[]): Uint8Array => {
const hash = createHmac('sha256', Buffer.from(key))
const hash = createHmac('sha256', key)
messages.forEach((m) => hash.update(m))
return Uint8Array.from(hash.digest())
}
Expand Down Expand Up @@ -164,7 +164,7 @@ const ecc = {
return necc.signSync(h, d, { der: false, extraEntropy: e })
},

signSchnorr: (h: Uint8Array, d: Uint8Array, e: Uint8Array = Buffer.alloc(32, 0x00)): Uint8Array => {
signSchnorr: (h: Uint8Array, d: Uint8Array, e: Uint8Array = new Uint8Array(32).fill(0x00)): Uint8Array => {
return necc.schnorr.signSync(h, d, e)
},

Expand Down
18 changes: 9 additions & 9 deletions packages/web3-wallet/src/password-crypto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ You should have received a copy of the GNU Lesser General Public License
along with the library. If not, see <http://www.gnu.org/licenses/>.
*/

import { Buffer } from 'buffer/'
import { binToHex, concatBytes, hexToBinUnsafe } from '@alephium/web3'
import {
randomBytes,
createCipheriv,
Expand All @@ -33,18 +33,18 @@ const ivByteLength = 64
const authTagLength = 16

export const encrypt = (password: string, dataRaw: string): string => {
const data = Buffer.from(dataRaw, 'utf8')
const data = new TextEncoder().encode(dataRaw)

const salt = randomBytes(saltByteLength)
const derivedKey = keyFromPassword(password, salt)
const iv = randomBytes(ivByteLength)
const cipher = createCipher(derivedKey, iv)
const encrypted = Buffer.concat([cipher.update(data), cipher.final()])
const encrypted = concatBytes([cipher.update(data), cipher.final()])
const authTag = cipher.getAuthTag()
const payload = {
salt: salt.toString('hex'),
iv: iv.toString('hex'),
encrypted: Buffer.concat([encrypted, authTag]).toString('hex'),
encrypted: binToHex(concatBytes([encrypted, authTag])),
version: 1
}

Expand All @@ -59,18 +59,18 @@ export const decrypt = (password: string, payloadRaw: string): string => {
throw new Error(`Invalid version: got ${version}, expected: 1`)
}

const salt = Buffer.from(payload.salt, 'hex')
const iv = Buffer.from(payload.iv, 'hex')
const encrypted = Buffer.from(payload.encrypted, 'hex')
const salt = hexToBinUnsafe(payload.salt)
const iv = hexToBinUnsafe(payload.iv)
const encrypted = hexToBinUnsafe(payload.encrypted)

const derivedKey = keyFromPassword(password, salt)
const decipher = createDecipher(derivedKey, iv)
const data = encrypted.slice(0, encrypted.length - authTagLength)
const authTag = encrypted.slice(encrypted.length - authTagLength, encrypted.length)
decipher.setAuthTag(authTag)
const decrypted = Buffer.concat([decipher.update(data), decipher.final()])
const decrypted = concatBytes([decipher.update(data), decipher.final()])

return decrypted.toString('utf8')
return new TextDecoder().decode(decrypted)
}

const createCipher = (key: CipherKey, iv: BinaryLike): CipherGCM => {
Expand Down
7 changes: 4 additions & 3 deletions packages/web3-wallet/src/privatekey-wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ along with the library. If not, see <http://www.gnu.org/licenses/>.

import { ec as EC } from 'elliptic'
import { Account, KeyType, ExplorerProvider, NodeProvider, SignerProviderSimple, utils, web3 } from '@alephium/web3'
import { publicKeyFromPrivateKey, addressFromPublicKey, groupOfAddress } from '@alephium/web3'
import { deriveHDWalletPrivateKey, deriveHDWalletPrivateKeyForGroup } from './hd-wallet'

const ec = new EC('secp256k1')
Expand Down Expand Up @@ -62,9 +63,9 @@ export class PrivateKeyWallet extends SignerProviderSimple {
super()
this.keyType = keyType ?? 'default'
this.privateKey = privateKey
this.publicKey = utils.publicKeyFromPrivateKey(privateKey, this.keyType)
this.address = utils.addressFromPublicKey(this.publicKey, this.keyType)
this.group = utils.groupOfAddress(this.address)
this.publicKey = publicKeyFromPrivateKey(privateKey, this.keyType)
this.address = addressFromPublicKey(this.publicKey, this.keyType)
this.group = groupOfAddress(this.address)
this.nodeProvider = nodeProvider ?? web3.getCurrentNodeProvider()
this.explorerProvider = explorerProvider ?? web3.getCurrentExplorerProvider()
}
Expand Down
6 changes: 1 addition & 5 deletions packages/web3-wallet/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,6 @@ module.exports = {
},
plugins: [
new webpack.SourceMapDevToolPlugin({ filename: '[file].map' }),
new webpack.ProvidePlugin({
Buffer: ['buffer', 'Buffer']
}),
new webpack.IgnorePlugin({
checkResource(resource) {
// The "bip39/src/wordlists" node module consists of json files for multiple languages. We only need English.
Expand All @@ -40,8 +37,7 @@ module.exports = {
fallback: {
fs: false,
stream: require.resolve('stream-browserify'),
crypto: require.resolve('crypto-browserify'),
buffer: require.resolve('buffer/')
crypto: require.resolve('crypto-browserify')
}
},
output: {
Expand Down
1 change: 0 additions & 1 deletion packages/web3/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@
"bignumber.js": "^9.1.1",
"blakejs": "1.2.1",
"bn.js": "5.2.1",
"buffer": "^6.0.3",
"cross-fetch": "^3.1.5",
"crypto-browserify": "^3.12.0",
"elliptic": "6.5.4",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import {
isAssetAddress,
isContractAddress
} from './address'
import { binToHex } from './utils'
import { binToHex } from '../utils'

describe('address', function () {
it('should validate address', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,11 @@ import { ec as EC } from 'elliptic'
import BN from 'bn.js'
import { TOTAL_NUMBER_OF_GROUPS } from '../constants'
import blake from 'blakejs'
import bs58 from './bs58'
import djb2 from './djb2'
import { binToHex, hexToBinUnsafe } from './utils'
import bs58 from '../utils/bs58'
import djb2 from '../utils/djb2'
import { binToHex, concatBytes, hexToBinUnsafe } from '../utils'
import { KeyType } from '../signer'
import { MultiSig, lockupScriptCodec } from '../codec/lockup-script-codec'
import { Buffer } from 'buffer/'
import { compactSignedIntCodec } from '../codec'

const ec = new EC('secp256k1')
Expand Down Expand Up @@ -54,7 +53,7 @@ function decodeAndValidateAddress(address: string): Uint8Array {
if (addressType === AddressType.P2MPKH) {
let multisig: MultiSig
try {
multisig = lockupScriptCodec.decode(Buffer.from(decoded)).script as MultiSig
multisig = lockupScriptCodec.decode(decoded).script as MultiSig
} catch (_) {
throw new Error(`Invalid multisig address: ${address}`)
}
Expand Down Expand Up @@ -163,26 +162,23 @@ export function addressFromPublicKey(publicKey: string, _keyType?: KeyType): str
const keyType = _keyType ?? 'default'

if (keyType === 'default') {
const addressType = Buffer.from([AddressType.P2PKH])
const hash = Buffer.from(blake.blake2b(Buffer.from(publicKey, 'hex'), undefined, 32))
const bytes = Buffer.concat([addressType, hash])
const hash = blake.blake2b(hexToBinUnsafe(publicKey), undefined, 32)
const bytes = new Uint8Array([AddressType.P2PKH, ...hash])
return bs58.encode(bytes)
} else {
const lockupScript = Buffer.from(`0101000000000458144020${publicKey}8685`, 'hex')
const lockupScript = hexToBinUnsafe(`0101000000000458144020${publicKey}8685`)
return addressFromScript(lockupScript)
}
}

export function addressFromScript(script: Uint8Array): string {
const scriptHash = blake.blake2b(script, undefined, 32)
const addressType = Buffer.from([AddressType.P2SH])
return bs58.encode(Buffer.concat([addressType, scriptHash]))
return bs58.encode(new Uint8Array([AddressType.P2SH, ...scriptHash]))
}

export function addressFromContractId(contractId: string): string {
const addressType = Buffer.from([AddressType.P2C])
const hash = Buffer.from(hexToBinUnsafe(contractId))
const bytes = Buffer.concat([addressType, hash])
const hash = hexToBinUnsafe(contractId)
const bytes = new Uint8Array([AddressType.P2C, ...hash])
return bs58.encode(bytes)
}

Expand All @@ -193,7 +189,7 @@ export function addressFromTokenId(tokenId: string): string {

export function contractIdFromTx(txId: string, outputIndex: number): string {
const txIdBin = hexToBinUnsafe(txId)
const data = Buffer.concat([txIdBin, Buffer.from([outputIndex])])
const data = new Uint8Array([...txIdBin, outputIndex])
const hash = blake.blake2b(data, undefined, 32)
return binToHex(hash)
}
Expand All @@ -202,10 +198,10 @@ export function subContractId(parentContractId: string, pathInHex: string, group
if (group < 0 || group >= TOTAL_NUMBER_OF_GROUPS) {
throw new Error(`Invalid group ${group}`)
}
const data = Buffer.concat([hexToBinUnsafe(parentContractId), hexToBinUnsafe(pathInHex)])
const bytes = Buffer.concat([
blake.blake2b(blake.blake2b(data, undefined, 32), undefined, 32).slice(0, -1),
Buffer.from([group])
const data = concatBytes([hexToBinUnsafe(parentContractId), hexToBinUnsafe(pathInHex)])
const bytes = new Uint8Array([
...blake.blake2b(blake.blake2b(data, undefined, 32), undefined, 32).slice(0, -1),
group
])
return binToHex(bytes)
}
Expand Down
19 changes: 19 additions & 0 deletions packages/web3/src/address/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/*
Copyright 2018 - 2022 The Alephium Authors
This file is part of the alephium project.

The library is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

The library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with the library. If not, see <http://www.gnu.org/licenses/>.
*/

export * from './address'
11 changes: 2 additions & 9 deletions packages/web3/src/api/node-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,8 @@ import {
requestWithLog
} from './types'
import { Api as NodeApi, CallContractFailed, CallContractSucceeded } from './api-alephium'
import {
HexString,
addressFromContractId,
addressFromTokenId,
groupOfAddress,
hexToString,
isHexString,
toNonNegativeBigInt
} from '../utils'
import { HexString, hexToString, isHexString, toNonNegativeBigInt } from '../utils'
import { addressFromContractId, addressFromTokenId, groupOfAddress } from '../address'
import * as node from '../api/api-alephium'

function initializeNodeApi(baseUrl: string, apiKey?: string, customFetch?: typeof fetch): NodeApi<string> {
Expand Down
4 changes: 2 additions & 2 deletions packages/web3/src/api/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ along with the library. If not, see <http://www.gnu.org/licenses/>.

import { ZERO_ADDRESS } from '../constants'
import { isDebugModeEnabled } from '../debug'
import { assertType, bs58, Eq, isBase58, isHexString } from '../utils'
import { assertType, binToHex, bs58, Eq, isBase58, isHexString } from '../utils'
import * as node from './api-alephium'

export type Number256 = bigint | string
Expand Down Expand Up @@ -93,7 +93,7 @@ export function toApiByteVec(v: Val): string {
try {
const address = bs58.decode(v)
if (address.length == 33 && address[0] == 3) {
return Buffer.from(address.slice(1)).toString('hex')
return binToHex(address.slice(1))
}
} catch (_) {
throw new Error(`Invalid hex-string: ${v}`)
Expand Down
7 changes: 3 additions & 4 deletions packages/web3/src/codec/array-codec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with the library. If not, see <http://www.gnu.org/licenses/>.
*/
import { Buffer } from 'buffer/'
import { Parser } from 'binary-parser'
import { compactSignedIntCodec, compactUnsignedIntCodec, DecodedCompactInt } from './compact-int-codec'
import { Codec } from './codec'
Expand All @@ -28,15 +27,15 @@ export interface DecodedArray<T> {
export class ArrayCodec<T> implements Codec<T[]> {
constructor(private childCodec: Codec<T>, public parser = ArrayCodec.arrayParser(childCodec.parser)) {}

encode(input: T[]): Buffer {
encode(input: T[]): Uint8Array {
const result = [...compactSignedIntCodec.encodeI256(BigInt(input.length))]
for (const element of input) {
result.push(...this.childCodec.encode(element))
}
return Buffer.from(result)
return new Uint8Array(result)
}

decode(input: Buffer): T[] {
decode(input: Uint8Array): T[] {
const result = this.parser.parse(input)
return result.value.map((v) => this.childCodec.decode(v.value))
}
Expand Down
Loading
Loading