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

Save serialized traces #547

Merged
merged 4 commits into from
Mar 11, 2025
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
241 changes: 150 additions & 91 deletions pkg/api/event_handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"encoding/hex"
"errors"
"fmt"
"github.com/tonkeeper/tongo/abi"
"go.uber.org/zap"
"golang.org/x/exp/slices"
"net/http"
Expand Down Expand Up @@ -390,29 +391,43 @@ func (h *Handler) EmulateMessageToAccountEvent(ctx context.Context, request *oas
if err != nil {
return nil, toError(http.StatusBadRequest, err)
}
configBase64, err := h.storage.TrimmedConfigBase64()
hash, err := c.HashString()
if err != nil {
return nil, toError(http.StatusInternalServerError, err)
}
options := []txemulator.TraceOption{
txemulator.WithAccountsSource(h.storage),
txemulator.WithConfigBase64(configBase64),
txemulator.WithLimit(1100),
}
if !params.IgnoreSignatureCheck.Value {
options = append(options, txemulator.WithSignatureCheck())
}
emulator, err := txemulator.NewTraceBuilder(options...)
if err != nil {
return nil, toError(http.StatusInternalServerError, err)
return nil, toError(http.StatusBadRequest, err)
}
tree, err := emulator.Run(ctx, m)
trace, version, _, err := h.storage.GetTraceWithState(ctx, hash)
if err != nil {
return nil, toProperEmulationError(err)
h.logger.Warn("get trace from storage: ", zap.Error(err))
}
trace, err := emulatedTreeToTrace(ctx, h.executor, h.storage, tree, emulator.FinalStates(), nil, h.configPool)
if err != nil {
return nil, toError(http.StatusInternalServerError, err)
if trace == nil || h.tongoVersion == 0 || version > h.tongoVersion {
configBase64, err := h.storage.TrimmedConfigBase64()
if err != nil {
return nil, toError(http.StatusInternalServerError, err)
}
options := []txemulator.TraceOption{
txemulator.WithAccountsSource(h.storage),
txemulator.WithConfigBase64(configBase64),
txemulator.WithLimit(1100),
}
if !params.IgnoreSignatureCheck.Value {
options = append(options, txemulator.WithSignatureCheck())
}
emulator, err := txemulator.NewTraceBuilder(options...)
if err != nil {
return nil, toError(http.StatusInternalServerError, err)
}
tree, err := emulator.Run(ctx, m)
if err != nil {
return nil, toProperEmulationError(err)
}
trace, err = emulatedTreeToTrace(ctx, h.executor, h.storage, tree, emulator.FinalStates(), nil, h.configPool)
if err != nil {
return nil, toError(http.StatusInternalServerError, err)
}
err = h.storage.SaveTraceWithState(ctx, hash, trace, h.tongoVersion, []abi.MethodInvocation{}, 24*time.Hour)
if err != nil {
fmt.Println("trace not saved: ", err)
}
}
actions, err := bath.FindActions(ctx, trace, bath.WithInformationSource(h.storage))
if err != nil {
Expand All @@ -437,33 +452,47 @@ func (h *Handler) EmulateMessageToEvent(ctx context.Context, request *oas.Emulat
}
trace, prs := h.mempoolEmulate.traces.Get(hash)
if !prs {
var m tlb.Message
if err := tlb.Unmarshal(c, &m); err != nil {
hs, err := c.HashString()
if err != nil {
return nil, toError(http.StatusBadRequest, err)
}
configBase64, err := h.storage.TrimmedConfigBase64()
trace, version, _, err := h.storage.GetTraceWithState(ctx, hs)
if err != nil {
return nil, toError(http.StatusInternalServerError, err)
}
options := []txemulator.TraceOption{
txemulator.WithAccountsSource(h.storage),
txemulator.WithConfigBase64(configBase64),
}
if !params.IgnoreSignatureCheck.Value {
options = append(options, txemulator.WithSignatureCheck())
h.logger.Warn("get trace from storage: ", zap.Error(err))
}
if trace == nil || h.tongoVersion == 0 || version > h.tongoVersion {
var m tlb.Message
if err := tlb.Unmarshal(c, &m); err != nil {
return nil, toError(http.StatusBadRequest, err)
}
configBase64, err := h.storage.TrimmedConfigBase64()
if err != nil {
return nil, toError(http.StatusInternalServerError, err)
}
options := []txemulator.TraceOption{
txemulator.WithAccountsSource(h.storage),
txemulator.WithConfigBase64(configBase64),
}
if !params.IgnoreSignatureCheck.Value {
options = append(options, txemulator.WithSignatureCheck())
}

emulator, err := txemulator.NewTraceBuilder(options...)
if err != nil {
return nil, toError(http.StatusInternalServerError, err)
}
tree, err := emulator.Run(ctx, m)
if err != nil {
return nil, toProperEmulationError(err)
}
trace, err = emulatedTreeToTrace(ctx, h.executor, h.storage, tree, emulator.FinalStates(), nil, h.configPool)
if err != nil {
return nil, toError(http.StatusInternalServerError, err)
emulator, err := txemulator.NewTraceBuilder(options...)
if err != nil {
return nil, toError(http.StatusInternalServerError, err)
}
tree, err := emulator.Run(ctx, m)
if err != nil {
return nil, toProperEmulationError(err)
}
trace, err = emulatedTreeToTrace(ctx, h.executor, h.storage, tree, emulator.FinalStates(), nil, h.configPool)
if err != nil {
return nil, toError(http.StatusInternalServerError, err)
}
err = h.storage.SaveTraceWithState(ctx, hs, trace, h.tongoVersion, []abi.MethodInvocation{}, 24*time.Hour)
if err != nil {
fmt.Println("trace not saved: ", err)
}
}
}
actions, err := bath.FindActions(ctx, trace, bath.WithInformationSource(h.storage))
Expand All @@ -489,34 +518,48 @@ func (h *Handler) EmulateMessageToTrace(ctx context.Context, request *oas.Emulat
}
trace, prs := h.mempoolEmulate.traces.Get(hash)
if !prs {
var m tlb.Message
err = tlb.Unmarshal(c, &m)
hs, err := c.HashString()
if err != nil {
return nil, toError(http.StatusBadRequest, err)
}
configBase64, err := h.storage.TrimmedConfigBase64()
trace, version, _, err := h.storage.GetTraceWithState(ctx, hs)
if err != nil {
return nil, toError(http.StatusInternalServerError, err)
}
options := []txemulator.TraceOption{
txemulator.WithAccountsSource(h.storage),
txemulator.WithConfigBase64(configBase64),
}
if !params.IgnoreSignatureCheck.Value {
options = append(options, txemulator.WithSignatureCheck())
h.logger.Warn("get trace from storage: ", zap.Error(err))
}
if trace == nil || h.tongoVersion == 0 || version > h.tongoVersion {
var m tlb.Message
err = tlb.Unmarshal(c, &m)
if err != nil {
return nil, toError(http.StatusBadRequest, err)
}
configBase64, err := h.storage.TrimmedConfigBase64()
if err != nil {
return nil, toError(http.StatusInternalServerError, err)
}
options := []txemulator.TraceOption{
txemulator.WithAccountsSource(h.storage),
txemulator.WithConfigBase64(configBase64),
}
if !params.IgnoreSignatureCheck.Value {
options = append(options, txemulator.WithSignatureCheck())
}

emulator, err := txemulator.NewTraceBuilder(options...)
if err != nil {
return nil, toError(http.StatusInternalServerError, err)
}
tree, err := emulator.Run(ctx, m)
if err != nil {
return nil, toProperEmulationError(err)
}
trace, err = emulatedTreeToTrace(ctx, h.executor, h.storage, tree, emulator.FinalStates(), nil, h.configPool)
if err != nil {
return nil, toError(http.StatusInternalServerError, err)
emulator, err := txemulator.NewTraceBuilder(options...)
if err != nil {
return nil, toError(http.StatusInternalServerError, err)
}
tree, err := emulator.Run(ctx, m)
if err != nil {
return nil, toProperEmulationError(err)
}
trace, err = emulatedTreeToTrace(ctx, h.executor, h.storage, tree, emulator.FinalStates(), nil, h.configPool)
if err != nil {
return nil, toError(http.StatusInternalServerError, err)
}
err = h.storage.SaveTraceWithState(ctx, hs, trace, h.tongoVersion, []abi.MethodInvocation{}, 24*time.Hour)
if err != nil {
fmt.Println("trace not saved: ", err)
}
}
}
t := convertTrace(trace, h.addressBook)
Expand Down Expand Up @@ -603,44 +646,60 @@ func (h *Handler) EmulateMessageToWallet(ctx context.Context, request *oas.Emula
if err != nil {
return nil, toError(http.StatusInternalServerError, err)
}
configBase64, err := h.storage.TrimmedConfigBase64()
if err != nil {
return nil, toError(http.StatusInternalServerError, err)
}

options := []txemulator.TraceOption{
txemulator.WithConfigBase64(configBase64),
txemulator.WithAccountsSource(h.storage),
txemulator.WithLimit(1100),
}
accounts, err := convertEmulationParameters(request.Params)
hash, err := msgCell.HashString()
if err != nil {
return nil, toError(http.StatusBadRequest, err)
}
var states []tlb.ShardAccount
for accountID, balance := range accounts {
originalState, err := h.storage.GetAccountState(ctx, accountID)
trace, version, _, err := h.storage.GetTraceWithState(ctx, hash)
if err != nil {
h.logger.Warn("get trace from storage: ", zap.Error(err))
}
if trace == nil || h.tongoVersion == 0 || version > h.tongoVersion {
configBase64, err := h.storage.TrimmedConfigBase64()
if err != nil {
return nil, toError(http.StatusInternalServerError, err)
}
state, err := prepareAccountState(*walletAddress, originalState, balance)

options := []txemulator.TraceOption{
txemulator.WithConfigBase64(configBase64),
txemulator.WithAccountsSource(h.storage),
txemulator.WithLimit(1100),
}
accounts, err := convertEmulationParameters(request.Params)
if err != nil {
return nil, toError(http.StatusBadRequest, err)
}
var states []tlb.ShardAccount
for accountID, balance := range accounts {
originalState, err := h.storage.GetAccountState(ctx, accountID)
if err != nil {
return nil, toError(http.StatusInternalServerError, err)
}
state, err := prepareAccountState(*walletAddress, originalState, balance)
if err != nil {
return nil, toError(http.StatusInternalServerError, err)
}
states = append(states, state)
}

options = append(options, txemulator.WithAccounts(states...))
emulator, err := txemulator.NewTraceBuilder(options...)
if err != nil {
return nil, toError(http.StatusInternalServerError, err)
}
states = append(states, state)
}
options = append(options, txemulator.WithAccounts(states...))
emulator, err := txemulator.NewTraceBuilder(options...)
if err != nil {
return nil, toError(http.StatusInternalServerError, err)
}
tree, err := emulator.Run(ctx, m)
if err != nil {
return nil, toProperEmulationError(err)
}
trace, err := emulatedTreeToTrace(ctx, h.executor, h.storage, tree, emulator.FinalStates(), nil, h.configPool)
if err != nil {
return nil, toError(http.StatusInternalServerError, err)
tree, err := emulator.Run(ctx, m)
if err != nil {
return nil, toProperEmulationError(err)
}
trace, err = emulatedTreeToTrace(ctx, h.executor, h.storage, tree, emulator.FinalStates(), nil, h.configPool)
if err != nil {
return nil, toError(http.StatusInternalServerError, err)
}
err = h.storage.SaveTraceWithState(ctx, hash, trace, h.tongoVersion, []abi.MethodInvocation{}, 24*time.Hour)
if err != nil {
fmt.Println("trace not saved: ", err)
}
}
t := convertTrace(trace, h.addressBook)
actions, err := bath.FindActions(ctx, trace, bath.ForAccount(*walletAddress), bath.WithInformationSource(h.storage))
Expand Down
7 changes: 7 additions & 0 deletions pkg/api/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package api
import (
"context"
"fmt"
"golang.org/x/exp/slog"
"sync"

"github.com/go-faster/errors"
Expand Down Expand Up @@ -51,6 +52,7 @@ type Handler struct {
mempoolEmulate mempoolEmulate
// ctxToDetails converts a request context to a details instance.
ctxToDetails ctxToDetails
tongoVersion int

// mempoolEmulateIgnoreAccounts, we don't track pending transactions for this list of accounts.
mempoolEmulateIgnoreAccounts map[tongo.AccountID]struct{}
Expand Down Expand Up @@ -218,6 +220,10 @@ func NewHandler(logger *zap.Logger, opts ...Option) (*Handler, error) {
if options.score == nil {
options.score = score.NewScore()
}
tongoVersion, err := GetPackageVersionInt("tongo")
if err != nil {
slog.Warn("unable to detect tongo version", "err", err)
}
return &Handler{
logger: logger,
storage: options.storage,
Expand All @@ -244,6 +250,7 @@ func NewHandler(logger *zap.Logger, opts ...Option) (*Handler, error) {
mempoolEmulateIgnoreAccounts: map[tongo.AccountID]struct{}{
tongo.MustParseAddress("0:0000000000000000000000000000000000000000000000000000000000000000").ID: {},
},
tongoVersion: tongoVersion,
blacklistedBocCache: cache.NewLRUCache[[32]byte, struct{}](100000, "blacklisted_boc_cache"),
getMethodsCache: cache.NewLRUCache[string, *oas.MethodExecutionResult](100000, "get_methods_cache"),
tonConnect: tonConnect,
Expand Down
4 changes: 4 additions & 0 deletions pkg/api/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package api
import (
"context"
"crypto/ed25519"
"time"

"github.com/tonkeeper/opentonapi/pkg/gasless"
"github.com/tonkeeper/opentonapi/pkg/oas"
Expand Down Expand Up @@ -111,6 +112,9 @@ type storage interface {
GetAccountMultisigs(ctx context.Context, accountID ton.AccountID) ([]core.Multisig, error)
GetMultisigByID(ctx context.Context, accountID ton.AccountID) (*core.Multisig, error)

SaveTraceWithState(ctx context.Context, msgHash string, trace *core.Trace, version int, getMethods []abi.MethodInvocation, ttl time.Duration) error
GetTraceWithState(ctx context.Context, msgHash string) (*core.Trace, int, []abi.MethodInvocation, error)

liteStorageRaw
}

Expand Down
31 changes: 31 additions & 0 deletions pkg/api/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ package api

import (
"fmt"
"runtime/debug"
"strconv"
"strings"

"github.com/tonkeeper/tongo/boc"
)
Expand All @@ -25,3 +28,31 @@ func deserializeSingleBoc(bocStr string) (*boc.Cell, error) {
}
return cells[0], nil
}

func GetPackageVersionInt(packagePath string) (int, error) {
info, ok := debug.ReadBuildInfo()
if !ok {
return 0, fmt.Errorf("error getting build info")
}

for _, dep := range info.Deps {
if strings.Contains(dep.Path, packagePath) {
version := strings.TrimPrefix(dep.Version, "v")

parts := strings.Split(version, ".")

result := 0
for _, part := range parts {
num, err := strconv.Atoi(part)
if err != nil {
return 0, fmt.Errorf("error parsing version number: %v", err)
}
result = result*100 + num
}

return result, nil
}
}

return 0, fmt.Errorf("package %s not found", packagePath)
}
Loading
Loading