forked from Militereum/Militereum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.pas
371 lines (335 loc) · 9.43 KB
/
server.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
unit server;
interface
uses
// Delphi
System.JSON,
System.SysUtils,
// Indy
IdContext,
IdCustomHTTPServer,
IdGlobal,
// Velthuis' BigNumbers
Velthuis.BigIntegers,
// project
web3;
type
IPayload = interface
function Id: BigInteger;
function Method: string;
function Params: TJsonArray;
function ToString: string;
end;
TOnRPC = procedure(
const aContext: TIdContext;
const aPayload: IPayload;
const callback: TProc<Boolean>;
const onError : TProc<IError>) of object;
TOnLog = procedure(const request, response: string; const success: Boolean) of object;
TEthereumRPCServer = class(TIdCustomHTTPServer)
strict private
FOnRPC: TOnRPC;
FOnLog: TOnLog;
procedure Block(
const aPayload: IPayload;
const aResponseInfo: TIdHTTPResponseInfo;
const aError: IError);
function Forward(
const aContext: TIdContext;
const aRequest: string;
const aResponseInfo: TIdHTTPResponseInfo): Boolean;
strict protected
procedure DoCommandGet(
aContext: TIdContext;
aRequestInfo: TIdHTTPRequestInfo;
aResponseInfo: TIdHTTPResponseInfo); override;
public
class function URI(const port: TIdPort): string;
property OnRPC: TOnRPC read FOnRPC write FOnRPC;
property OnLog: TOnLog read FOnLog write FOnLog;
end;
function ports(num: Integer): IResult<TArray<TIdPort>>;
function start: IResult<TEthereumRPCServer>; overload;
function start(const port: TIdPort): IResult<TEthereumRPCServer>; overload;
function start(const ports: TArray<TIdPort>): IResult<TEthereumRPCServer>; overload;
implementation
uses
// Delphi
System.Classes,
// Indy
IdException,
IdGlobalProtocols,
// web3
web3.http,
web3.json,
// project
common,
thread;
const
MAX_PORT_NO = 65535 - 1024;
MIN_PORT_NO = 1024;
function ports(num: Integer): IResult<TArray<TIdPort>>;
begin
var output: TArray<TIdPort> := [];
var port := MAX_PORT_NO;
while True do
begin
const server = TIdCustomHTTPServer.Create;
try
server.DefaultPort := port;
try
server.Active := True;
except
on E: Exception do
begin
if E is EIdCouldNotBindSocket and (server.DefaultPort > MIN_PORT_NO) then
port := port - 1
else
begin
Result := TResult<TArray<TIdPort>>.Err(TError.Create(E.Message));
EXIT;
end;
end;
end;
if server.Active then
try
output := output + [server.DefaultPort];
if Length(output) >= num then
begin
Result := TResult<TArray<TIdPort>>.Ok(output);
EXIT;
end;
if server.DefaultPort > MIN_PORT_NO then
port := port - 1
else
begin
Result := TResult<TArray<TIdPort>>.Err(System.SysUtils.Format('ports out of range %d..%d', [MIN_PORT_NO, MAX_PORT_NO]));
EXIT;
end;
finally
server.Active := False;
end;
finally
server.Free;
end;
end;
end;
function start: IResult<TEthereumRPCServer>;
begin
var port := MAX_PORT_NO;
while True do
begin
const server = TEthereumRPCServer.Create;
server.DefaultPort := port;
try
server.Active := True;
except
on E: Exception do
begin
if E is EIdCouldNotBindSocket and (server.DefaultPort > MIN_PORT_NO) then
port := port - 1
else
begin
Result := TResult<TEthereumRPCServer>.Err(TError.Create(E.Message));
EXIT;
end;
end;
end;
if not server.Active then
server.Free
else
begin
Result := TResult<TEthereumRPCServer>.Ok(server);
EXIT;
end;
end;
end;
function start(const port: TIdPort): IResult<TEthereumRPCServer>;
begin
const server = TEthereumRPCServer.Create;
server.DefaultPort := port;
try
server.Active := True;
except
on E: Exception do
begin
Result := TResult<TEthereumRPCServer>.Err(TError.Create(E.Message));
EXIT;
end;
end;
Result := TResult<TEthereumRPCServer>.Ok(server);
end;
function start(const ports: TArray<TIdPort>): IResult<TEthereumRPCServer>;
begin
if Length(ports) = 0 then
begin
Result := TResult<TEthereumRPCServer>.Err('nothing to do');
EXIT;
end;
if Length(ports) = 1 then
begin
Result := start(ports[0]);
EXIT;
end;
const server = TEthereumRPCServer.Create;
for var I := 0 to High(ports) do server.Bindings.Add.Port := ports[I];
try
server.Active := True;
except
on E: Exception do
begin
Result := TResult<TEthereumRPCServer>.Err(TError.Create(E.Message));
EXIT;
end;
end;
Result := TResult<TEthereumRPCServer>.Ok(server);
end;
type
TPayload = class(TInterfacedObject, IPayload)
strict private
FObject: TJsonObject;
public
function Id: BigInteger;
function Method: string;
function Params: TJsonArray;
function ToString: string; override;
constructor Create(aObject: TJsonValue);
destructor Destroy; override;
end;
constructor TPayload.Create(aObject: TJsonValue);
begin
inherited Create;
FObject := aObject.Clone as TJsonObject;
end;
destructor TPayload.Destroy;
begin
if Assigned(FObject) then FObject.Free;
inherited Destroy;
end;
function TPayload.Id: BigInteger;
begin
Result := web3.json.getPropAsBigInt(FObject, 'id');
end;
function TPayload.Method: string;
begin
Result := web3.json.getPropAsStr(FObject, 'method');
end;
function TPayload.Params: TJsonArray;
begin
Result := web3.json.getPropAsArr(FObject, 'params');
end;
function TPayload.ToString: string;
begin
Result := System.SysUtils.Format('{"jsonrpc":"2.0","method":"%s","params":%s,"id":%s}', [Self.Method, web3.json.marshal(Self.Params), Self.Id.ToString(10)]);
end;
{ TEthereumRPCServer }
procedure TEthereumRPCServer.DoCommandGet(
aContext: TIdContext;
aRequestInfo: TIdHTTPRequestInfo;
aResponseInfo: TIdHTTPResponseInfo);
type
TForward = (Allow, Wait, Block);
begin
const body = (function(const aRequestInfo: TIdHTTPRequestInfo): string
begin
Result := '';
if not Assigned(aRequestInfo.PostStream) then
EXIT;
const SS = TStringStream.Create;
try
SS.CopyFrom(aRequestInfo.PostStream, 0);
Result := SS.DataString.Trim;
finally
SS.Free;
end;
end)(aRequestInfo);
const &object = web3.json.unmarshal(body);
if Assigned(&object) then
try
if web3.json.getPropAsStr(&object, 'jsonrpc') <> '' then
begin
const payload: IPayload = TPayload.Create(&object);
if Assigned(FOnRPC) then
begin
thread.lock(Self, procedure
begin
var error: IError := nil;
var status := TForward.Wait;
FOnRPC(aContext, payload,
procedure(allow: Boolean)
begin
if allow then
status := TForward.Allow
else
status := TForward.Block;
end,
procedure(err: IError) begin error := err end);
while (status = TForward.Wait) and not Assigned(error) do TThread.Sleep(100);
const success = (function: Boolean
begin
Result := not Assigned(error);
if (status = TForward.Block) or not Result then
Self.Block(payload, aResponseInfo, error)
else
Result := Self.Forward(aContext, body, aResponseInfo);
end)();
if Assigned(FOnLog) then FOnLog(body, aResponseInfo.ContentText.Trim, success);
end);
EXIT;
end;
end;
finally
&object.Free;
end;
const success = Self.Forward(aContext, body, aResponseInfo);
if Assigned(FOnLog) then FOnLog(body, aResponseInfo.ContentText.Trim, success);
end;
procedure TEthereumRPCServer.Block(
const aPayload: IPayload;
const aResponseInfo: TIdHTTPResponseInfo;
const aError: IError);
begin
aResponseInfo.ResponseNo := 405;
if Assigned(aError) then
aResponseInfo.ContentText := System.SysUtils.Format('{"jsonrpc":"2.0","error":{"code":-32000,"message":"%s"},"id":%s}', [aError.Message, aPayload.Id.ToString(10)])
else
aResponseInfo.ContentText := System.SysUtils.Format('{"jsonrpc":"2.0","error":{"code":-32601,"message":"method not allowed"},"id":%s}', [aPayload.Id.ToString(10)]);
end;
function TEthereumRPCServer.Forward(
const aContext: TIdContext;
const aRequest: string;
const aResponseInfo: TIdHTTPResponseInfo): Boolean;
begin
const endpoint = Self.endpoint(aContext.Binding.Port);
Result := endpoint.isOk;
if not Result then
aResponseInfo.ContentText := endpoint.Error.Message
else begin
const response = web3.http.post(endpoint.Value, aRequest, common.Headers);
Result := response.isOk;
if not Result then begin
var err: IHttpError;
if Supports(response.Error, IHttpError, err) then aResponseInfo.ResponseNo := err.StatusCode;
aResponseInfo.ContentText := response.Error.Message;
end else begin
aResponseInfo.ContentText := response.Value.ContentAsString(TEncoding.UTF8);
const &object = web3.json.unmarshal(aResponseInfo.ContentText);
if Assigned(&object) then
try
Result := not Assigned(web3.json.getPropAsObj(&object, 'error'));
finally
&object.Free;
end;
end;
end;
end;
class function TEthereumRPCServer.URI(const port: TIdPort): string;
begin
Result := System.SysUtils.Format('http://%s:%d', [(function: string
begin
if IndyComputerName <> '' then
Result := IndyComputerName.ToLower
else
Result := 'localhost';
end)(), port]);
end;
end.