Skip to content

Instantly share code, notes, and snippets.

@TrueCarry
Last active April 25, 2024 10:41
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save TrueCarry/cac00bfae051f7028085aa018c2a05c6 to your computer and use it in GitHub Desktop.
Save TrueCarry/cac00bfae051f7028085aa018c2a05c6 to your computer and use it in GitHub Desktop.
TON Connect V2 Proof verification
async function check(req, res) {
const walletInfo = req.body.walletInfo as Wallet
if (!walletInfo?.connectItems?.tonProof) {
return res.status(httpStatus.BAD_REQUEST).send({ ok: false })
}
const proof = walletInfo.connectItems.tonProof as TonProofItemReplySuccess
if (!proof) {
return res.status(httpStatus.BAD_REQUEST).send({ ok: false })
}
const { data } = await axios(
`https://${
walletInfo.account.chain === '-3' ? 'testnet.' : ''
}tonapi.io/v1/wallet/getWalletPublicKey?account=${encodeURI(walletInfo.account.address)}`
)
const pubkey = Buffer.from(data.publicKey, 'hex')
const parsedMessage = ConvertTonProofMessage(walletInfo, proof)
const checkMessage = await CreateMessage(parsedMessage)
const verifyRes = SignatureVerify(pubkey, checkMessage, parsedMessage.Signature)
if (!verifyRes) {
return res.status(httpStatus.BAD_REQUEST).send({ ok: false })
}
}
import { TonProofItemReplySuccess } from '@tonconnect/protocol'
import { Wallet } from '@tonconnect/sdk'
import { createHash } from 'crypto'
import { Address } from 'ton'
import nacl from 'tweetnacl'
interface Domain {
LengthBytes: number // uint32 `json:"lengthBytes"`
Value: string // string `json:"value"`
}
interface ParsedMessage {
Workchain: number // int32
Address: Buffer // []byte
Timstamp: number // int64
Domain: Domain // Domain
Signature: Buffer // []byte
Payload: string // string
StateInit: string // string
}
export function SignatureVerify(pubkey: Buffer, message: Buffer, signature: Buffer): boolean {
return nacl.sign.detached.verify(message, signature, pubkey)
// return ed25519.Verify(pubkey, message, signature)
}
const tonProofPrefix = 'ton-proof-item-v2/'
const tonConnectPrefix = 'ton-connect'
export async function CreateMessage(message: ParsedMessage): Promise<Buffer> {
// wc := make([]byte, 4)
// binary.BigEndian.PutUint32(wc, uint32(message.Workchain))
const wc = Buffer.alloc(4)
wc.writeUint32BE(message.Workchain)
// ts := make([]byte, 8)
// binary.LittleEndian.PutUint64(ts, uint64(message.Timstamp))
const ts = Buffer.alloc(8)
ts.writeBigUint64LE(BigInt(message.Timstamp))
// dl := make([]byte, 4)
// binary.LittleEndian.PutUint32(dl, message.Domain.LengthBytes)
const dl = Buffer.alloc(4)
dl.writeUint32LE(message.Domain.LengthBytes)
const m = Buffer.concat([
Buffer.from(tonProofPrefix),
wc,
message.Address,
dl,
Buffer.from(message.Domain.Value),
ts,
Buffer.from(message.Payload),
])
// const messageHash = //sha256.Sum256(m)
// const messageHash = await crypto.subtle.digest('SHA-256', m)
// const m = Buffer.from(tonProofPrefix)
// m.write(ts)
// m := []byte(tonProofPrefix)
// m = append(m, wc...)
// m = append(m, message.Address...)
// m = append(m, dl...)
// m = append(m, []byte(message.Domain.Value)...)
// m = append(m, ts...)
// m = append(m, []byte(message.Payload)...)
const messageHash = createHash('sha256').update(m).digest()
const fullMes = Buffer.concat([
Buffer.from([0xff, 0xff]),
Buffer.from(tonConnectPrefix),
Buffer.from(messageHash),
])
// []byte{0xff, 0xff}
// fullMes = append(fullMes, []byte(tonConnectPrefix)...)
// fullMes = append(fullMes, messageHash[:]...)
// const res = await crypto.subtle.digest('SHA-256', fullMes)
const res = createHash('sha256').update(fullMes).digest()
return Buffer.from(res)
}
export function ConvertTonProofMessage(
walletInfo: Wallet,
tp: TonProofItemReplySuccess
): ParsedMessage {
const address = Address.parse(walletInfo.account.address)
const res: ParsedMessage = {
Workchain: address.workChain,
Address: address.hash,
Domain: {
LengthBytes: tp.proof.domain.lengthBytes,
Value: tp.proof.domain.value,
},
Signature: Buffer.from(tp.proof.signature, 'base64'),
Payload: tp.proof.payload,
StateInit: walletInfo.account.walletStateInit,
Timstamp: tp.proof.timestamp,
}
return res
}
@howardpen9
Copy link

nice.

So can we say we still have Wallet Signing to trigged the external message in TON>?

@huuduynvc
Copy link

how to parse state init

@y0unghe
Copy link

y0unghe commented Dec 5, 2023

How to create and send ton_proof message from front-end?

@0dd-b1t
Copy link

0dd-b1t commented Feb 11, 2024

Well, tonapi returns 404 on that address. Is there a new approach to check the tonproof?

@petrosyan52
Copy link

Well, tonapi returns 404 on that address. Is there a new approach to check the tonproof?

You need to use ton api v2
https://docs.tonconsole.com/tonapi/api-v2
use
v2/accounts/{account_id}/publickey

@peng-xiao-shuai
Copy link

1712115842224
1712115842237
Figure 1 shows me making a request on the test network and getting public_key
Figure 2 shows that I made a request on the mainnet and couldn't get publick_key

I used the tonkeeper Google Wallet to get the address.
Does anyone know why?

@peng-xiao-shuai
Copy link

public_key can be obtained using v2/tonconnect/stateinit

const { data } = await axios(
    `https://${
      body.network === '-3' ? 'testnet.' : ''
    }tonapi.io/v2/tonconnect/stateinit`,
    {
      method: 'POST',
      data: {
        state_init: body.proof.state_init,
      },
    }
  )

@AlexBSoft
Copy link

@peng-xiao-shuai thanks, that works!

Is there any other methods to get public key instead of tonapi.io? It is proprietary project and they can shutdown v2 api in few years how did they did it with v1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment