Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
tbruyelle committed Dec 2, 2024
1 parent baaa55f commit 682a6fc
Show file tree
Hide file tree
Showing 5 changed files with 250 additions and 15 deletions.
110 changes: 101 additions & 9 deletions deposit_throttling.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
package main

import (
"context"
"fmt"
"io"
"log"
"math"
"net/http"
"os"
"path/filepath"
"strconv"
"time"

"github.com/chromedp/chromedp"
"github.com/go-echarts/go-echarts/v2/charts"
"github.com/go-echarts/go-echarts/v2/components"
"github.com/go-echarts/go-echarts/v2/opts"
"github.com/go-echarts/go-echarts/v2/types"
"github.com/pkg/browser"
)

const (
Expand All @@ -22,30 +27,88 @@ const (
)

func depositThrottling() error {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
boundaryName := "x5789h"
// send multi-part header
w.Header().Set("Content-Type", fmt.Sprintf("multipart/x-mixed-replace; boundary=%s", boundaryName))
w.WriteHeader(http.StatusOK)

nbBlocks := 100
for {
select {
case <-r.Context().Done():
fmt.Println("STOP")
return
default:
fmt.Println("RENDER BLOCK", nbBlocks)
filename, err := genChartFile(nbBlocks)
if err != nil {
panic(err)
}

bz, err := toPNG(r.Context(), filename)
if err != nil {
panic(err)
}

// start boundary
io.WriteString(w, fmt.Sprintf("--%s\n", boundaryName))
io.WriteString(w, "Content-Type: image/png\n")
io.WriteString(w, fmt.Sprintf("Content-Length: %d\n\n", len(bz)))

if _, err := w.Write(bz); err != nil {
log.Printf("failed to write mjpeg image: %s", err)
return
}

// close boundary
if _, err := io.WriteString(w, "\n"); err != nil {
log.Printf("failed to write boundary: %s", err)
return
}
}
time.Sleep(time.Second)
nbBlocks++
}
})

http.ListenAndServe(":8080", nil)
return nil
}

func generateLineData(data []int) []opts.LineData {
items := make([]opts.LineData, len(data))
for i, v := range data {
items[i] = opts.LineData{Value: v}
}
return items
}

func genChartFile(nbBlocks int) (string, error) {
f, err := os.CreateTemp("", "chart*.html")
if err != nil {
return err
return "", err
}
defer f.Close()
page := components.NewPage()
page.PageTitle = "Deposit throttling"
page.AddCharts(
newLineChart(100),
newLineChart(nbBlocks),
)
page.Render(f)
fmt.Printf("Charts rendered in %s\n", f.Name())
browser.OpenFile(f.Name())
return nil
// browser.OpenFile(f.Name())
return f.Name(), nil
}

func newLineChart(nbBlocks int) components.Charter {
// create a new line instance
line := charts.NewLine()
line.Animation = false
// set some global options like Title/Legend/ToolTip or anything else
line.SetGlobalOptions(
charts.WithDataZoomOpts(opts.DataZoom{XAxisIndex: 0, Start: 0, End: 100, Type: "slider"}),
// charts.WithDataZoomOpts(opts.DataZoom{XAxisIndex: 0, Start: 0, End: 100, Type: "slider"}),
charts.WithInitializationOpts(opts.Initialization{
Theme: types.ThemeWesteros,
// Theme: types.ThemeWesteros,
Height: "700px",
}),
charts.WithTitleOpts(opts.Title{
Expand Down Expand Up @@ -151,3 +214,32 @@ func generateDeposits(numProposals []opts.LineData) []opts.LineData {
}
return items
}

func toPNG(ctx context.Context, file string) ([]byte, error) {
// get full path of file
abs, _ := filepath.Abs(file)

// create context
ctx, cancel := chromedp.NewContext(
ctx,
// chromedp.WithDebugf(log.Printf),
)
defer cancel()

// screenshot buffer
var buf []byte

// capture entire browser viewport, returning png with quality=100
task := chromedp.Tasks{
// use file:// for a local file
chromedp.Navigate("file://" + abs),
// set resolution for screenshot
chromedp.EmulateViewport(1200, 800),
// take screenshot
chromedp.FullScreenshot(&buf, 100),
}

// run tasks
err := chromedp.Run(ctx, task)
return buf, err
}
17 changes: 17 additions & 0 deletions docs/deposit.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<html>
<head>
<script src="https://go-echarts.github.io/go-echarts-assets/assets/echarts.min.js"></script>
</head>
NumProposals <input type=number id="numProposals" min=0 value=0 /><br>
Alpha UP <input id="alphaUp" value='0.1' /><br>
Alpha DOWN <input id="alphaDown" value='0.05' /><br>
k <input type=number id="k" value='1' />
<body>
<style> .container {display: flex;justify-content: center;align-items: center;} .item {margin: auto;} </style>
<div class="container">
<div class="item" id="main" style="width:900px;height:700px;"></div>
</div>

<script src="deposit.js" ></script>
</body>
</html>
100 changes: 100 additions & 0 deletions docs/deposit.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
var chartDom = document.getElementById('main');
var myChart = echarts.init(chartDom);
var option;

let nbBlocks = 0
let defaultDeposit=250
let deposits = [];
let numProposals = []
let N = 2
for (var i = 0; i < nbBlocks; i++) {
deposits.push({value:[i,defaultDeposit]});
numProposals.push({value:[i,0]});
}
option = {
title: {
text: 'Deposit throttling'
},
tooltip: {
trigger: 'axis',
formatter: function (params) {
return 'height='+ params[0].data.value[0] +
' n=' + params[1].data.value[1] +
' D=' + params[0].data.value[1]
},
axisPointer: {
animation: false
}
},
xAxis: {
name: 'Block height',
// type: 'value',
},
yAxis: [
{
name: 'Deposit',
type: 'value',
boundaryGap: [0, '25%'],
// splitLine: {
// show: false
// }
},
{
name: 'Num proposals',
type: 'value',
Show: false,
min: 0,
max: 6,
// splitLine: {
// show: false
// }
},
],
};

function computeDeposit(n) {
let lastDeposit = defaultDeposit
if (deposits.length>0) {
lastDeposit = deposits[deposits.length-1].value[1]
}
let alpha = parseFloat(document.getElementById('alphaUp').value);
let beta = 0
if (n <= N) {
alpha = parseFloat(document.getElementById('alphaDown').value);
beta = -1
}
let k = parseFloat(document.getElementById('k').value);
let v = (n - N + beta) ** (1/k)

D = lastDeposit * (1 + alpha * v)
console.log("D="+D)
if (D < defaultDeposit) {
D = defaultDeposit
}
return D
}

setInterval(function () {
nbBlocks++
n = parseInt(document.getElementById('numProposals').value);
// deposits.shift();
deposits.push({ value:[ nbBlocks, computeDeposit(n) ] });
// numProposals.shift();
numProposals.push({ value:[ nbBlocks, n ] })
myChart.setOption({
series: [
{
type: 'line',
data: deposits,
},
{
type: 'line',
data: numProposals,
yAxisIndex: 1,
}
]
});
}, 1000);

option && myChart.setOption(option);

14 changes: 10 additions & 4 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ go 1.23

require (
github.com/atomone-hub/atomone v0.0.0-20240925165552-b9631ed2e3b7
github.com/chromedp/chromedp v0.11.2
github.com/cometbft/cometbft v0.37.5
github.com/cosmos/cosmos-sdk v0.47.13
github.com/cosmos/gogoproto v1.4.10
Expand Down Expand Up @@ -34,6 +35,8 @@ require (
github.com/btcsuite/btcd/btcec/v2 v2.3.2 // indirect
github.com/cespare/xxhash v1.1.0 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/chromedp/cdproto v0.0.0-20241022234722-4d5d5faf59fb // indirect
github.com/chromedp/sysutil v1.1.0 // indirect
github.com/cockroachdb/errors v1.10.0 // indirect
github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect
github.com/cockroachdb/pebble v1.0.0 // indirect
Expand All @@ -57,6 +60,9 @@ require (
github.com/go-kit/kit v0.12.0 // indirect
github.com/go-kit/log v0.2.1 // indirect
github.com/go-logfmt/logfmt v0.6.0 // indirect
github.com/gobwas/httphead v0.1.0 // indirect
github.com/gobwas/pool v0.2.1 // indirect
github.com/gobwas/ws v1.4.0 // indirect
github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/glog v1.2.0 // indirect
Expand All @@ -77,12 +83,14 @@ require (
github.com/huandu/skiplist v1.2.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/jmhodges/levigo v1.0.0 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/klauspost/compress v1.17.0 // indirect
github.com/kr/pretty v0.3.1 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/libp2p/go-buffer-pool v0.1.0 // indirect
github.com/linxGnu/grocksdb v1.8.11 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.9 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect
Expand Down Expand Up @@ -121,7 +129,7 @@ require (
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
golang.org/x/net v0.23.0 // indirect
golang.org/x/sync v0.6.0 // indirect
golang.org/x/sys v0.18.0 // indirect
golang.org/x/sys v0.26.0 // indirect
golang.org/x/term v0.18.0 // indirect
golang.org/x/text v0.14.0 // indirect
google.golang.org/genproto v0.0.0-20240123012728-ef4313101c80 // indirect
Expand All @@ -137,9 +145,7 @@ require (
)

// stick with compatible version or x/exp in v0.47.x line
replace (
golang.org/x/exp => golang.org/x/exp v0.0.0-20230711153332-06a737ee72cb
)
replace golang.org/x/exp => golang.org/x/exp v0.0.0-20230711153332-06a737ee72cb

// prevent error 'used for two different module paths'
exclude github.com/coinbase/rosetta-sdk-go v0.7.9
Loading

0 comments on commit 682a6fc

Please sign in to comment.