Compare commits

..

1 commit

Author SHA1 Message Date
1eca8232e0 add backend files 2024-01-08 15:29:02 +03:00
22 changed files with 103 additions and 974 deletions

489
.gitignore vendored Executable file → Normal file
View file

@ -21,492 +21,3 @@
# Go workspace file
go.work
# Created by https://www.toptal.com/developers/gitignore/api/rider
# Edit at https://www.toptal.com/developers/gitignore?templates=rider
### Rider ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
# End of https://www.toptal.com/developers/gitignore/api/rider
# Created by https://www.toptal.com/developers/gitignore/api/visualstudio
# Edit at https://www.toptal.com/developers/gitignore?templates=visualstudio
### VisualStudio ###
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
*.log
*.tlog
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio 6 auto-generated project file (contains which files were open etc.)
*.vbp
# Visual Studio 6 workspace and project file (working project files containing files to include in project)
*.dsw
*.dsp
# Visual Studio 6 technical files
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# Visual Studio History (VSHistory) files
.vshistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# VS Code files for those working on multiple tools
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
*.code-workspace
# Local History for Visual Studio Code
.history/
# Windows Installer files from build outputs
*.cab
*.msi
*.msix
*.msm
*.msp
# JetBrains Rider
*.sln.iml
### VisualStudio Patch ###
# Additional files built by Visual Studio
# End of https://www.toptal.com/developers/gitignore/api/visualstudio

0
.idea/.gitignore generated vendored Executable file → Normal file
View file

0
.idea/Blog.iml generated Executable file → Normal file
View file

0
.idea/modules.xml generated Executable file → Normal file
View file

0
.idea/vcs.xml generated Executable file → Normal file
View file

View file

@ -1,139 +0,0 @@
package Comment
import (
"github.com/nspcc-dev/neo-go/pkg/interop"
"github.com/nspcc-dev/neo-go/pkg/interop/iterator"
"github.com/nspcc-dev/neo-go/pkg/interop/native/gas"
"github.com/nspcc-dev/neo-go/pkg/interop/native/std"
"github.com/nspcc-dev/neo-go/pkg/interop/runtime"
"github.com/nspcc-dev/neo-go/pkg/interop/storage"
)
type Comment struct {
id string
userLogin string
postId string
text string
likes int
}
const (
comment_prefix = "comment_"
user_comment_count_prefix = "comment_count_"
gas_decimals = 1_0000_0000
comment_hash = "comment_hash"
)
func _deploy(data interface{}, isUpdate bool) {
if isUpdate {
return
}
ctx := storage.GetContext()
storage.Put(ctx, "index_comment", "0")
}
func CreateNewComment(userLogin string, postId string, text string) {
ctx := storage.GetContext()
id := std.Atoi10(storage.Get(ctx, "index_comment").(string))
id++
storage.Put(ctx, "index_comment", std.Itoa10(id))
if storage.Get(ctx, user_comment_count_prefix+userLogin) == nil {
storage.Put(ctx, user_comment_count_prefix+userLogin, 0)
}
commentId := comment_prefix + std.Itoa10(id)
newComment := Comment{
id: commentId,
userLogin: userLogin,
postId: postId,
text: text,
likes: 0,
}
var comments = make([]Comment, 0)
comments = GetByPostId(postId)
comments = append(comments, newComment)
storage.Put(ctx, comment_prefix+postId, std.Serialize(comments)) // { "comment_post_{i} : comments.json"}
storage.Put(ctx, commentId, std.Serialize(newComment)) // { "comment_{i}" : comment.json}
commentCount := storage.Get(ctx, user_comment_count_prefix+userLogin).(int)
commentCount++
storage.Put(ctx, user_comment_count_prefix+userLogin, commentCount) // { "comment_count_{login}" : {i} }
storage.Put(ctx, userLogin+"_c_"+std.Itoa10(commentCount), commentId) // { "{login}_c_{i} : comment_{i} }
runtime.Log("Comment created: " + commentId + " ----- " + user_comment_count_prefix + userLogin + " ------ " + userLogin + "_c_" + std.Itoa10(commentCount))
}
func GetByPostId(postId string) []Comment {
ctx := storage.GetContext()
comments := storage.Get(ctx, comment_prefix+postId)
if comments == nil {
storage.Put(ctx, comment_prefix+postId, std.Serialize(make([]Comment, 0)))
}
return std.Deserialize(storage.Get(ctx, comment_prefix+postId).([]byte)).([]Comment)
}
func GetByLoginInPost(postId string, login string) []Comment {
comments := GetByPostId(postId)
var commentsByAuthor []Comment
for _, comment := range comments {
if comment.userLogin == login {
commentsByAuthor = append(commentsByAuthor, comment)
}
}
return commentsByAuthor
}
func GetByLogin(login string) []Comment {
var comments []Comment = make([]Comment, 0)
ctx := storage.GetContext()
it := storage.Find(ctx, login+"_c_", storage.ValuesOnly|storage.DeserializeValues)
for iterator.Next(it) {
commentId := iterator.Value(it).(string)
comments = append(comments, GetComment(commentId))
}
return comments
}
func GetComment(commentId string) Comment {
ctx := storage.GetContext()
comment := storage.Get(ctx, commentId)
if comment == nil {
panic("comment not found")
}
return std.Deserialize(comment.([]byte)).(Comment)
}
func Rate(commentId string, walletHashFrom interop.Hash160) {
ctx := storage.GetContext()
comment := GetComment(commentId)
success := gas.Transfer(walletHashFrom, storage.Get(ctx, comment.userLogin+"_hash").(interop.Hash160), gas_decimals, nil)
if !success {
panic("gas transfer failed")
} else {
comment.likes += 1
updateComment(comment)
}
}
func updateComment(comment Comment) {
ctx := storage.GetContext()
comments := GetByPostId(comment.postId)
for i := 0; i < len(comments); i++ {
if comments[i].id == comment.id {
comments[i] = comment
}
}
storage.Put(ctx, comment_prefix+comment.postId, std.Serialize(comments))
storage.Put(ctx, comment.id, std.Serialize(comment))
}
func GetContractHash() interop.Hash160 {
ctx := storage.GetContext()
return storage.Get(ctx, comment_hash).(interop.Hash160)
}

View file

@ -0,0 +1,8 @@
package Comments
type Comments struct {
authorId string
text string
likes int
dislikes int
}

5
Forum/forum_contract.go Normal file
View file

@ -0,0 +1,5 @@
package Forums
type Forum struct {
threads []string
}

0
Models/categories.json Executable file → Normal file
View file

8
Post/go.mod Normal file
View file

@ -0,0 +1,8 @@
module Post
go 1.21.5
require (
github.com/google/uuid v1.5.0
github.com/nspcc-dev/neo-go/pkg/interop v0.0.0-20231127165613-b35f351f0ba0
)

4
Post/go.sum Normal file
View file

@ -0,0 +1,4 @@
github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU=
github.com/google/uuid v1.5.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/nspcc-dev/neo-go/pkg/interop v0.0.0-20231127165613-b35f351f0ba0 h1:N+dMIBmteXjJpkH6UZ7HmNftuFxkqszfGLbhsEctnv0=
github.com/nspcc-dev/neo-go/pkg/interop v0.0.0-20231127165613-b35f351f0ba0/go.mod h1:J/Mk6+nKeKSW4wygkZQFLQ6SkLOSGX5Ga0RuuuktEag=

2
Comment/comment.yml → Post/neo-go.yml Executable file → Normal file
View file

@ -1,4 +1,4 @@
name: comment
name: Post
sourceurl: http://example.com/
safemethods: []
supportedstandards: []

139
Post/post_contract.go Executable file → Normal file
View file

@ -1,137 +1,68 @@
package Post
package Posts
import (
"github.com/nspcc-dev/neo-go/pkg/interop"
"github.com/nspcc-dev/neo-go/pkg/interop/iterator"
"github.com/nspcc-dev/neo-go/pkg/interop/native/gas"
guuid "github.com/google/uuid"
"github.com/nspcc-dev/neo-go/pkg/interop/native/std"
"github.com/nspcc-dev/neo-go/pkg/interop/runtime"
"github.com/nspcc-dev/neo-go/pkg/interop/storage"
//"github.com/nspcc-dev/neo-go/pkg/interop/runtime"
)
type Post struct {
postName string
text string
login string
likes int
threadId string
id string
header string
text string
authorId string
hashTags []string
category string
likes int
dislikes int
}
const (
lastIndex = "user_post_index"
id = "current_post_id"
comment_prefix = "comment_"
gas_decimals = 1_0000_0000
)
const storeURLKey = "storeURL"
func _deploy(data interface{}, isUpdate bool) {
if isUpdate {
return
}
func NewPost(login string, text string, postName string) {
ctx := storage.GetContext()
updatePostId()
id := storage.Get(ctx, id).(int)
post_id := "post_" + std.Itoa10(id)
storeURL := "https://codeberg.org/NaMe2te/Blog/src/branch/master/Posts/posts_storage.json"
storage.Put(ctx, storeURLKey, storeURL)
}
func NewPost(authorId string, text string, hashTags []string, threadId string) {
ctx := storage.GetContext()
post := Post{
text: text,
login: login,
hashTags: hashTags,
authorId: authorId,
dislikes: 0,
likes: 0,
postName: postName,
id: post_id,
category: "none",
threadId: threadId,
id: guuid.New(),
}
storage.Put(ctx, post.id, std.Serialize(post))
updatePostIndex(login)
lastPostIndex := storage.Get(ctx, login+lastIndex).(int)
storage.Put(ctx, login+"_p_"+std.Itoa10(lastPostIndex), post.id)
runtime.Log("Post created. Post id: " + post.id + "; User post id" + login + "_p_" + std.Itoa10(lastPostIndex))
}
func GetAllPosts() []Post {
posts := make([]Post, 0)
ctx := storage.GetReadOnlyContext()
it := storage.Find(ctx, "post", storage.ValuesOnly|storage.DeserializeValues)
for iterator.Next(it) {
post := iterator.Value(it).(Post)
runtime.Log(string(std.Serialize(post)))
posts = append(posts, post)
}
return posts
}
func GetPost(postId string) Post {
ctx := storage.GetReadOnlyContext()
data := storage.Get(ctx, postId)
if data == nil {
panic("post not found")
panic("player not found")
}
return std.Deserialize(data.([]byte)).(Post)
}
func GetAllPostsByUser(login string) []Post {
ctx := storage.GetReadOnlyContext()
var postsByUser []Post = make([]Post, 0)
i := 1
n := getPostIndex(login)
for i < n+1 {
post_key := storage.Get(ctx, login+"_p_"+std.Itoa10(i))
if post_key == nil {
panic("post key not found")
}
post_key = post_key.(string)
post := storage.Get(ctx, post_key)
if post == nil {
panic("post not found")
}
i++
postsByUser = append(postsByUser, std.Deserialize(post.([]byte)).(Post))
}
return postsByUser
}
func Rate(postId string, walletHashFrom interop.Hash160) {
ctx := storage.GetContext()
func RatePost(isLike bool, postId string) {
post := GetPost(postId)
success := gas.Transfer(walletHashFrom, storage.Get(ctx, post.login+"_hash").(interop.Hash160), gas_decimals, nil)
if !success {
panic("gas transfer failed")
if isLike {
post.likes++
} else {
post.likes += 1
post.dislikes++
}
storage.Put(ctx, post.id, std.Serialize(post))
}
}
func getPostIndex(userId string) int {
ctx := storage.GetContext()
index := storage.Get(ctx, userId+lastIndex)
if index == nil {
index = 0
}
return index.(int)
}
func updatePostIndex(userId string) {
ctx := storage.GetContext()
index := getPostIndex(userId)
storage.Put(ctx, userId+lastIndex, index+1)
}
func getPostId() int {
ctx := storage.GetContext()
current_id := storage.Get(ctx, id)
if current_id == nil {
current_id = 0
}
return current_id.(int)
}
func updatePostId() {
ctx := storage.GetContext()
cur_id := getPostId()
storage.Put(ctx, id, cur_id+1)
}

View file

@ -1,6 +0,0 @@
name: Post
safemethods: []
supportedstandards: []
events:
permissions:
- methods: "*"

0
README.md Executable file → Normal file
View file

View file

@ -2,9 +2,7 @@ package Users
import (
"github.com/nspcc-dev/neo-go/pkg/interop"
"github.com/nspcc-dev/neo-go/pkg/interop/contract"
"github.com/nspcc-dev/neo-go/pkg/interop/native/std"
"github.com/nspcc-dev/neo-go/pkg/interop/runtime"
"github.com/nspcc-dev/neo-go/pkg/interop/storage"
)
@ -14,14 +12,12 @@ type User struct {
login string
password string
ownerHash interop.Hash160
likes int
}
const (
lastIndex = "_lastIndex"
)
func NewUser(name string, surname string, login string, password string, owner interop.Hash160) {
ctx := storage.GetContext()
existing_login := storage.Get(ctx, login)
if existing_login != nil {
panic("this login is taken by someone else")
@ -33,22 +29,13 @@ func NewUser(name string, surname string, login string, password string, owner i
login: login,
password: password,
ownerHash: owner,
likes: 0,
}
saveUser(ctx, login, user)
}
func GetUser(login string) User {
return getUserTst(storage.GetReadOnlyContext(), login)
}
func RateForGas(commentId string, contractHash interop.Hash160, login string) {
ctx := storage.GetContext()
contract.Call(contractHash, "rate", contract.ReadOnly, commentId, storage.Get(ctx, login+"_hash"))
}
func getUserTst(ctx storage.Context, login string) User {
func GetUser(ctx storage.Context, login string) User {
data := storage.Get(ctx, login)
if data == nil {
@ -59,8 +46,13 @@ func getUserTst(ctx storage.Context, login string) User {
}
func saveUser(ctx storage.Context, userLogin string, user User) {
runtime.Log("User " + userLogin + " was created")
storage.Put(ctx, userLogin+"_hash", user.ownerHash)
storage.Put(ctx, userLogin, std.Serialize(user))
}
//TODO ну тит типа будет там ну типа число пистов типа да типо число комментов и типо тд типо
// func CountUserStatistic(User user) map[string]string {
// return userStats
// }
//TODO ну я хз как пойдет но мб надо написать сохранение поста через юзера, если варик с кринж конкатом строк не залетит
//func AddPostToUsersPostList(string postHash){}

View file

@ -1,210 +1,24 @@
import http.server
import socketserver
import subprocess
from urllib.parse import urlparse, parse_qs
import base64
import json
import re
def compile_and_deploy_contract(
user_path: str,
post_path: str,
comment_path: str,
password: str,
node_wallet: str,
run_start_funcs: bool=False
) -> dict[str, str]:
user_compile_command = f"sshpass -p {password} neo-go contract compile -i {user_path}/user.go -c {user_path}/user.yml -m {user_path}/user.json"
subprocess.run(user_compile_command, shell=True, check=False)
user_deploy_command = f"sshpass -p {password} neo-go contract deploy -i {user_path}/user.nef -w {node_wallet} -r http://localhost:30333 -m {user_path}/user.json --force"
proc = subprocess.Popen(user_deploy_command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
user_out_list = []
while True:
line = proc.stdout.readline()
if not line:
break
user_out_list.append(line.rstrip())
user_hash = str(user_out_list[-1], encoding='utf-8').replace("Contract: ", "")
post_compile_command = f"sshpass -p {password} neo-go contract compile -i {post_path}/post_contract.go -c {post_path}/post_contract.yml -m {post_path}/post_contract.json"
subprocess.run(post_compile_command, shell=True, check=False)
post_deploy_command = f"sshpass -p {password} neo-go contract deploy -i {post_path}/post_contract.nef -w {node_wallet} -r http://localhost:30333 -m {post_path}/post_contract.json --force"
proc = subprocess.Popen(post_deploy_command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
post_out_list = []
while True:
line = proc.stdout.readline()
if not line:
break
post_out_list.append(line.rstrip())
post_hash = str(post_out_list[-1], encoding='utf-8').replace("Contract: ", "")
comment_compile_command = f"sshpass -p {password} neo-go contract compile -i {comment_path}/comment.go -c {comment_path}/comment.yml -m {comment_path}/comment.json"
subprocess.run(comment_compile_command, shell=True, check=False)
comment_deploy_command = f"sshpass -p {password} neo-go contract deploy -i {comment_path}/comment.nef -w {node_wallet} -r http://localhost:30333 -m {comment_path}/comment.json --force"
proc = subprocess.Popen(comment_deploy_command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
comment_out_list = []
while True:
line = proc.stdout.readline()
if not line:
break
comment_out_list.append(line.rstrip())
comment_hash = str(comment_out_list[-1], encoding='utf-8').replace("Contract: ", "")
print(user_hash, post_hash, comment_hash)
if run_start_funcs:
comment_deploy_command = f"sshpass -p {password} neo-go contract invokefunction -w {node_wallet} -r http://localhost:30333 {user_hash} newUser user_test1 user_test1 user_test1 1 Nhfg3TbpwogLvDGVvAvqyThbsHgoSUKwtn --force"
proc = subprocess.Popen(comment_deploy_command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
comment_deploy_command = f"sshpass -p {password} neo-go contract invokefunction -w {node_wallet} -r http://localhost:30333 {user_hash} newUser user_test2 user_test2 user_test2 1 Nhfg3TbpwogLvDGVvAvqyThbsHgoSUKwtn --force"
proc = subprocess.Popen(comment_deploy_command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
comment_deploy_command = f"sshpass -p {password} neo-go contract invokefunction -w {node_wallet} -r http://localhost:30333 {post_hash} newPost user_test1 test test --force"
proc = subprocess.Popen(comment_deploy_command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
comment_deploy_command = f"sshpass -p {password} neo-go contract invokefunction -w {node_wallet} -r http://localhost:30333 {post_hash} newPost user_test2 test test --force"
proc = subprocess.Popen(comment_deploy_command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
comment_deploy_command = f"sshpass -p {password} neo-go contract invokefunction -w {node_wallet} -r http://localhost:30333 {comment_hash} createNewComment user_test1 post_1 some_text --force"
proc = subprocess.Popen(comment_deploy_command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
comment_deploy_command = f"sshpass -p {password} neo-go contract invokefunction -w {node_wallet} -r http://localhost:30333 {comment_hash} createNewComment user_test1 post_1 some_text --force"
proc = subprocess.Popen(comment_deploy_command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
comment_deploy_command = f"sshpass -p {password} neo-go contract invokefunction -w {node_wallet} -r http://localhost:30333 {comment_hash} createNewComment user_test2 post_1 some_text --force"
proc = subprocess.Popen(comment_deploy_command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
return user_hash, post_hash, comment_hash
user_hash, post_hash, comment_hash = compile_and_deploy_contract(
"../User",
"../Post",
"../Comment",
"one",
"/home/ftmi-krasotka/Desktop/frostfs_test/frostfs-aio/morph/node-wallet.json",
True
)
class MyHttpRequestHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
with open("./route.json", "r") as f:
route_dict = json.load(f)
with open("logs.log", "w") as f:
f.write("starting...")
with open("logs.log", "a") as f:
f.write(f"user_hash: {user_hash}\npost_hash: {post_hash}\ncomment_hash: {comment_hash}")
parsed_path = urlparse(self.path)
query = parse_qs(parsed_path.query)
print(query)
if "command_type" in query and "command_id" in query:
if 'command' in query and 'args' in query:
self.send_response(200)
self.send_header("Content-type", "text/html")
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header('Content-type', 'text/html')
self.end_headers()
params = query.get("args", None)
parsed_params = " " + ' '.join(params) if params else ""
command_type = query["command_type"][0]
contract_name = query["contract"][0]
method = query["method"][0]
with open("logs.log", "a") as f:
f.write("reading params...\n")
if command_type == "get":
hash_for_req = None
if contract_name == "post":
hash_for_req = post_hash
elif contract_name == "user":
hash_for_req = user_hash
elif contract_name == "comment":
hash_for_req = comment_hash
with open("logs.log", "a") as f:
f.write(f"params: {[command_type, contract_name, method, parsed_params]}\n")
command = f"neo-go contract testinvokefunction -r http://localhost:30333 {hash_for_req} {method}{parsed_params}"
print(command)
proc = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out_list = []
while True:
if proc.stdout is None:
break
line = proc.stdout.readline()
if not line:
break
out_list.append(line.rstrip())
answer = " ".join(map(lambda x: x.decode("utf-8"), out_list))
answer = re.sub(r"[\n\t\s]*", "", answer)
print(json.loads(answer)["stack"][0])
if json.loads(answer)["stack"][0]["type"] == "Struct":
answer_dict = json.loads(answer)["stack"][0]["value"]
obj_fiedls = []
for field in answer_dict:
if field["type"] in ["ByteString", "Buffer"]:
encoded_string = field["value"]
result_string = base64.b64decode(encoded_string)
try:
result_string = result_string.decode('utf-8')
except:
pass
obj_fiedls.append(result_string)
elif field["type"] == "Integer":
encoded_string = field["value"]
obj_fiedls.append(encoded_string)
self.wfile.write(bytes(f"{obj_fiedls}", "utf-8"))
else:
answer_dict = json.loads(answer)["stack"][0]["value"]
answer_list = []
for obj_i in answer_dict:
obj = obj_i["value"]
obj_fiedls = []
for field in obj:
if field["type"] in ["ByteString", "Buffer"]:
encoded_string = field["value"]
result_string = base64.b64decode(encoded_string)
result_string = result_string.decode('utf-8')
obj_fiedls.append(result_string)
elif field["type"] == "Integer":
encoded_string = field["value"]
obj_fiedls.append(encoded_string)
answer_list.append(obj_fiedls)
self.wfile.write(bytes(f"{answer_list}", "utf-8"))
self.wfile.write(bytes(f"command: {query['command']}, args: {query['args']}", "utf-8"))
else:
self.send_response(400)
self.send_header("Content-type", "text/html")
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(bytes("Bad request", "utf-8"))
if __name__ == "__main__":
PORT = 2281
Handler = MyHttpRequestHandler

View file

@ -55,14 +55,6 @@ route = {
"func_name": "name of invoked func",
"parameters": "list([]) of func parameters"
}
},
"8": {
"command": "neo-go contract testinvokefunction",
"flags": {
"contract_hash": "hash of contract",
"func_name": "name of invoked func",
"parameters": "list([]) of func parameters"
}
}
}

View file

@ -1,14 +1,7 @@
import requests
# Отправляем GET запрос на сервер
response = requests.get(
'http://localhost:2281',
params={
"command_type": "get",
"method": "getPost",
"command_id": "8",
"contract": "post",
"args": ["post_1"]})
response = requests.get('http://localhost:2281', params={"command": 0, "args": {"amount_1": 1, "amount": 1}})
# Выводим ответ от сервера
print('Ответ от сервера:', response.text)

View file

@ -1 +1 @@
{"1": {"command": "neo-go wallet init", "flags": {"wallet": "wallet file name", "account": "create new account"}}, "2": {"command": "neo-go wallet dump-keys", "flags": {"wallet": "wallet file name"}}, "3": {"command": "neo-go wallet nep17 balance", "flags": {"wallet": "wallet file name"}}, "4": {"command": "neo-go wallet nep17 transfer", "flags": {"wallet": "wallet file name(wallet from which transfer is made)", "from": "hash of wallet from which transfer is made", "to": "hash of wallet to which transfer is made", "amount": "gas transfer amount", "token": "token for transfer NEO/GAS"}}, "5": {"command": "neo-go contract compile", "flags": {"in": "smart contract file name(*.go)", "manifest": "contract manifest file name(*.json)", "contract_config": "contract config file name(*.yml)"}}, "6": {"command": "neo-go contract deploy", "flags": {"wallet": "wallet file name", "in": "compiled smart contract file name(*.nef)", "manifest": "manifest file name(*.json)"}}, "7": {"command": "neo-go contract invokefunction", "flags": {"wallet": "wallet file name", "contract_hash": "hash of contract", "func_name": "name of invoked func", "parameters": "list([]) of func parameters"}}, "8": {"command": "neo-go contract testinvokefunction", "flags": {"contract_hash": "hash of contract", "func_name": "name of invoked func", "parameters": "list([]) of func parameters"}}}
{"1": {"command": "neo-go wallet init", "flags": {"wallet": "wallet file name", "account": "create new account"}}, "2": {"command": "neo-go wallet dump-keys", "flags": {"wallet": "wallet file name"}}, "3": {"command": "neo-go wallet nep17 balance", "flags": {"wallet": "wallet file name"}}, "4": {"command": "neo-go wallet nep17 transfer", "flags": {"wallet": "wallet file name(wallet from which transfer is made)", "from": "hash of wallet from which transfer is made", "to": "hash of wallet to which transfer is made", "amount": "gas transfer amount", "token": "token for transfer NEO/GAS"}}, "5": {"command": "neo-go contract compile", "flags": {"in": "smart contract file name(*.go)", "manifest": "contract manifest file name(*.json)", "contract_config": "contract config file name(*.yml)"}}, "6": {"command": "neo-go contract deploy", "flags": {"wallet": "wallet file name", "in": "compiled smart contract file name(*.nef)", "manifest": "manifest file name(*.json)"}}, "7": {"command": "neo-go contract invokefunction", "flags": {"wallet": "wallet file name", "contract_hash": "hash of contract", "func_name": "name of invoked func", "parameters": "list([]) of func parameters"}}}

2
go.mod Executable file → Normal file
View file

@ -3,5 +3,7 @@ module blog
go 1.21.5
require (
github.com/google/uuid v1.5.0
github.com/nspcc-dev/neo-go v0.104.0
github.com/nspcc-dev/neo-go/pkg/interop v0.0.0-20231219060339-de98b39a9502
)

14
go.sum Executable file → Normal file
View file

@ -1,2 +1,16 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU=
github.com/google/uuid v1.5.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/nspcc-dev/neo-go v0.104.0 h1:FGj3Z46yABcFIAI1SCLd1jQSoh+B00h/2VAgEgY1JKQ=
github.com/nspcc-dev/neo-go v0.104.0/go.mod h1:omsUK5PAtG2/nQ3/evs95QEg3wtkj3LH53e0NKtXVwQ=
github.com/nspcc-dev/neo-go/pkg/interop v0.0.0-20231219060339-de98b39a9502 h1:HwR9fWkdJXCbsTnrb2Rm92xkDGdEM0VHvZV+7XJUXM0=
github.com/nspcc-dev/neo-go/pkg/interop v0.0.0-20231219060339-de98b39a9502/go.mod h1:J/Mk6+nKeKSW4wygkZQFLQ6SkLOSGX5Ga0RuuuktEag=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc=
golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=