Skip to content
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## Unreleased

- added: (Houdini) Pay a pasted Zcash unified address out to its transparent receiver

## 2.61.0 (2026-11-13)

- changed: (Houdini) Rename provider from HoudiniSwap to Houdini, including its order link
Expand Down
1 change: 1 addition & 0 deletions package-lock.json

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

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
},
"dependencies": {
"@cosmjs/encoding": "^0.32.2",
"@noble/hashes": "^1.4.0",
"@scure/base": "^1.2.6",
"@ton/core": "0.59.1",
"@unizen-io/unizen-contract-addresses": "^0.0.15",
Expand Down
41 changes: 31 additions & 10 deletions src/swap/central/houdini.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import {
nativeToDenomination,
snooze
} from '../../util/utils'
import { getUnifiedTransparentAddress } from '../../util/zcashUnifiedAddress'
import {
asNumberString,
EdgeSwapRequestPlugin,
Expand Down Expand Up @@ -97,6 +98,28 @@ const addressTypeMap: StringMap = {
*/
const ZCASH_TRANSPARENT_ADDRESS = /^t1[1-9A-HJ-NP-Za-km-z]{33}$/

/**
* The Zcash address an order pays out to: a t1 address as-is, or the t1
* receiver of a unified `u1` address. Houdini would answer anything else with
* a bare validation failure (a unified address alone overruns its 200
* character limit), so those fail here with a clear message instead. That
* includes a unified address whose only transparent receiver is P2SH (t3).
*/
function getZcashOrderAddress(address: string): string {
if (ZCASH_TRANSPARENT_ADDRESS.test(address)) return address
let transparent: string | undefined
try {
transparent = getUnifiedTransparentAddress(address)
} catch (error: unknown) {
// Not a mainnet unified address, so it gets the same message as any
// other address Houdini would refuse.
}
if (transparent == null || !ZCASH_TRANSPARENT_ADDRESS.test(transparent)) {
throw new Error('Houdini supports transparent (t1) Zcash addresses only')
}
return transparent
}

/**
* A swap-to-address destination arrives as a core-built synthetic wallet whose
* id carries this prefix. Synthetic wallets hold the caller's destination
Expand Down Expand Up @@ -708,14 +731,12 @@ export function makeHoudiniPlugin(opts: EdgeCorePluginOptions): EdgeSwapPlugin {
throw new SwapCurrencyError(swapInfo, request)
}

// A unified address is longer than Houdini's address field allows, so the
// API would only answer with a bare "maxLength 200":
if (
toWallet.currencyInfo.pluginId === 'zcash' &&
!ZCASH_TRANSPARENT_ADDRESS.test(toAddress)
) {
throw new Error('Houdini supports transparent (t1) Zcash addresses only')
}
// The order pays out to an address Houdini accepts, while the saved action
// keeps the address the user entered:
const orderAddress =
toWallet.currencyInfo.pluginId === 'zcash'
? getZcashOrderAddress(toAddress)
: toAddress

// The quote amount is in the display units of whichever side the caller
// fixed: the `from` amount normally, or the `to` (receive) amount for a
Expand Down Expand Up @@ -1008,7 +1029,7 @@ export function makeHoudiniPlugin(opts: EdgeCorePluginOptions): EdgeSwapPlugin {
continue
}
const orderBody = {
addressTo: toAddress,
addressTo: orderAddress,
quoteId: candidate.quoteId,
refundAddress: fromAddress,
...(destinationTag == null ? {} : { destinationTag })
Expand Down Expand Up @@ -1186,7 +1207,7 @@ export function makeHoudiniPlugin(opts: EdgeCorePluginOptions): EdgeSwapPlugin {
method: 'POST',
body: JSON.stringify({
addressFrom: fromAddress,
addressTo: toAddress,
addressTo: orderAddress,
quoteId: candidate.quoteId,
signatures: [],
...(destinationTag == null ? {} : { destinationTag })
Expand Down
156 changes: 156 additions & 0 deletions src/util/zcashUnifiedAddress.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import { blake2b } from '@noble/hashes/blake2b'
import { sha256 } from '@noble/hashes/sha256'
import { bech32m, createBase58check } from '@scure/base'

// ZIP-316 unified address decoding, limited to what a payout needs: the
// transparent receiver, re-encoded as the t1 (P2PKH) or t3 (P2SH) address it
// stands for. Mainnet only.

const UNIFIED_HRP = 'u'
const PADDING_LENGTH = 16
const MIN_JUMBLE_LENGTH = 48

const P2PKH_TYPECODE = 0x00
const P2SH_TYPECODE = 0x01
const TRANSPARENT_RECEIVER_LENGTH = 20

// Mainnet Base58Check version prefixes for t1 and t3 addresses:
const P2PKH_PREFIX = [0x1c, 0xb8]
const P2SH_PREFIX = [0x1c, 0xbd]

const base58check = createBase58check(sha256)

const xorInto = (target: Uint8Array, mask: Uint8Array): Uint8Array =>
target.map((byte, i) => byte ^ mask[i])

const personalization = (prefix: string, suffix: number[]): Uint8Array =>
Uint8Array.from([...Array.from(prefix, c => c.charCodeAt(0)), ...suffix])

// F4Jumble's H_i: BLAKE2b with an output length of `length` bytes.
const jumbleH = (
round: number,
input: Uint8Array,
length: number
): Uint8Array =>
blake2b(input, {
dkLen: length,
personalization: personalization('UA_F4Jumble_H', [round, 0, 0])
})

// F4Jumble's G_i: 64-byte BLAKE2b blocks, counted by a little-endian u16,
// joined and cut to `length` bytes.
const jumbleG = (
round: number,
input: Uint8Array,
length: number
): Uint8Array => {
const out = new Uint8Array(Math.ceil(length / 64) * 64)
for (let block = 0; block * 64 < length; block++) {
const hash = blake2b(input, {
dkLen: 64,
personalization: personalization('UA_F4Jumble_G', [
round,
block & 0xff,
block >> 8
])
})
out.set(hash, block * 64)
}
return out.subarray(0, length)
}

// Variable names follow the ZIP-316 F4Jumble definition.
const f4JumbleInverse = (message: Uint8Array): Uint8Array => {
const leftLength = Math.min(64, Math.floor(message.length / 2))
const c = message.subarray(0, leftLength)
const d = message.subarray(leftLength)
const y = xorInto(c, jumbleH(1, d, leftLength))
const x = xorInto(d, jumbleG(1, y, d.length))
const a = xorInto(y, jumbleH(0, x, leftLength))
const b = xorInto(x, jumbleG(0, a, x.length))
const out = new Uint8Array(message.length)
out.set(a)
out.set(b, leftLength)
return out
}

// Bitcoin compactSize, which is how ZIP-316 encodes typecodes and lengths.
const readCompactSize = (
bytes: Uint8Array,
offset: number
): { value: number; offset: number } => {
const first = bytes[offset]
if (first == null) throw new Error('Truncated unified address')
if (first < 0xfd) return { value: first, offset: offset + 1 }
if (first === 0xfd && offset + 3 <= bytes.length) {
const value = bytes[offset + 1] | (bytes[offset + 2] << 8)
if (value < 0xfd) throw new Error('Non-canonical unified address')
return { value, offset: offset + 3 }
}
throw new Error('Unsupported unified address item size')
}

/**
* Returns the transparent receiver of a mainnet unified address as a t1
* (P2PKH) or t3 (P2SH) address, or undefined when the address has none.
* Throws when the input is not a valid mainnet unified address.
*/
export const getUnifiedTransparentAddress = (
address: string
): string | undefined => {
// The type wants a separator up front; `decode` checks for it anyway:
const { prefix, words } = bech32m.decode(
address as `${string}1${string}`,
false
)
if (prefix !== UNIFIED_HRP) {
throw new Error(`Not a mainnet unified address: ${prefix}`)
}
const jumbled = bech32m.fromWords(words)
if (jumbled.length < MIN_JUMBLE_LENGTH) {
throw new Error('Unified address is too short')
}
const decoded = f4JumbleInverse(jumbled)

const padding = decoded.subarray(decoded.length - PADDING_LENGTH)
const expectedPadding = new Uint8Array(PADDING_LENGTH)
expectedPadding[0] = UNIFIED_HRP.charCodeAt(0)
if (padding.some((byte, i) => byte !== expectedPadding[i])) {
throw new Error('Invalid unified address padding')
}

const items = decoded.subarray(0, decoded.length - PADDING_LENGTH)
let transparent: string | undefined
let lastTypecode = -1
let offset = 0
while (offset < items.length) {
const typecode = readCompactSize(items, offset)
const length = readCompactSize(items, typecode.offset)
const end = length.offset + length.value
if (end > items.length) throw new Error('Truncated unified address')
const value = items.subarray(length.offset, end)
offset = end

// ZIP-316 items are unique, in ascending typecode order, and hold at
// most one transparent receiver:
if (typecode.value <= lastTypecode) {
throw new Error('Unified address items are out of order')
}
lastTypecode = typecode.value
if (typecode.value !== P2PKH_TYPECODE && typecode.value !== P2SH_TYPECODE) {
Comment thread
j0ntz marked this conversation as resolved.
Resolved
continue
}
if (transparent != null) {
throw new Error('Unified address has two transparent receivers')
}
if (value.length !== TRANSPARENT_RECEIVER_LENGTH) {
throw new Error('Invalid transparent receiver length')
}
const versionPrefix =
typecode.value === P2PKH_TYPECODE ? P2PKH_PREFIX : P2SH_PREFIX
transparent = base58check.encode(
Uint8Array.from([...versionPrefix, ...value])
)
}
return transparent
}
65 changes: 62 additions & 3 deletions test/houdini.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,16 @@ const makeFakeSyntheticDestination = (params: {
const ZCASH_TRANSPARENT_ADDRESS = 't1Hsc1LR8yKnbbe3twRp88p6vFfC5t7DLbs'
const ZCASH_SAPLING_ADDRESS =
'zs1z7rejlpsa98s2rrrfkwmaxu53e4ue0ulcrw0h4x5g8jl04tak0d3mm47vdtahatqrlkngh9sly'
const ZCASH_UNIFIED_ADDRESS = `u1${'q'.repeat(211)}`
/** A ZIP-316 test vector with a P2PKH receiver, and that receiver's t1. */
const ZCASH_UNIFIED_ADDRESS =
'u1pg2aaph7jp8rpf6yhsza25722sg5fcn3vaca6ze27hqjw7jvvhhuxkpcg0ge9xh6drsgdkda8qjq5chpehkcpxf87rnjryjqwymdheptpvnljqqrjqzjwkc2ma6hcq666kgwfytxwac8eyex6ndgr6ezte66706e3vaqrd25dzvzkc69kw0jgywtd0cmq52q5lkw6uh7hyvzjse8ksx'
const ZCASH_UNIFIED_RECEIVER = 't1cN2ZVWzWcVRrnfeQzmkpLhzQ4dYRv8yRY'
/** A ZIP-316 test vector with shielded receivers only. */
const ZCASH_SHIELDED_UNIFIED_ADDRESS =
'u1ay3aawlldjrmxqnjf5medr5ma6p3acnet464ht8lmwplq5cd3ugytcmlf96rrmtgwldc75x94qn4n8pgen36y8tywlq6yjk7lkf3fa8wzjrav8z2xpxqnrnmjxh8tmz6jhfh425t7f3vy6p4pd3zmqayq49efl2c4xydc0gszg660q9p'
/** A unified address whose transparent receiver is P2SH (t3). */
const ZCASH_P2SH_UNIFIED_ADDRESS =
'u1pcx39dfudzx9uaas89vu34vgna22q0nz3hgcvx46y87uev2e0f74cr3vd2ukgj0u9fsng2j68hfdyzu0s76k4gdwj6u9mh3fla6kum859dt8z7dgsw5n747lwaxaf0n982yxw56zlxj'

/** 1300 S, the send amount the sim drive used. */
const SONIC_NATIVE_AMOUNT = '1300000000000000000000'
Expand Down Expand Up @@ -1303,8 +1312,58 @@ describe('houdini offline behaviors', function () {
expect(action.payoutWalletId).equals(zcashWallet.id)
})

it('refuses a Zcash address that is not transparent before quoting', async function () {
for (const toAddress of [ZCASH_UNIFIED_ADDRESS, ZCASH_SAPLING_ADDRESS]) {
it('pays a pasted unified address out to its transparent receiver', async function () {
const zcashDestination = makeFakeSyntheticDestination({
pluginId: 'zcash',
currencyCode: 'ZEC',
decimals: 8,
toAddress: ZCASH_UNIFIED_ADDRESS
})
const run = makeScriptedPlugin({
nativeAddress: '',
quotes: [privateQuote]
})
await quoteSonicToStellar(run, ({
toWallet: zcashDestination
} as unknown) as Partial<EdgeSwapRequest>)

expect(JSON.parse(run.orderBodies[0]).addressTo).equals(
ZCASH_UNIFIED_RECEIVER
)
const action = capture.savedAction as Record<string, unknown>
expect(action.actionType).equals('swapSend')
expect(action.payoutAddress).equals(ZCASH_UNIFIED_ADDRESS)
})

it('pays a pasted transparent address out unchanged', async function () {
const zcashDestination = makeFakeSyntheticDestination({
pluginId: 'zcash',
currencyCode: 'ZEC',
decimals: 8,
toAddress: ZCASH_TRANSPARENT_ADDRESS
})
const run = makeScriptedPlugin({
nativeAddress: '',
quotes: [privateQuote]
})
await quoteSonicToStellar(run, ({
toWallet: zcashDestination
} as unknown) as Partial<EdgeSwapRequest>)

expect(JSON.parse(run.orderBodies[0]).addressTo).equals(
ZCASH_TRANSPARENT_ADDRESS
)
const action = capture.savedAction as Record<string, unknown>
expect(action.payoutAddress).equals(ZCASH_TRANSPARENT_ADDRESS)
})

it('refuses a Zcash address without a t1 receiver before quoting', async function () {
for (const toAddress of [
ZCASH_SHIELDED_UNIFIED_ADDRESS,
ZCASH_P2SH_UNIFIED_ADDRESS,
ZCASH_SAPLING_ADDRESS,
`u1${'q'.repeat(211)}`
]) {
const zcashDestination = makeFakeSyntheticDestination({
pluginId: 'zcash',
currencyCode: 'ZEC',
Expand Down
Loading
Loading